.NET Diary

October 9, 2013

static vs. const vs. readOnly

Filed under: All, ASP.NET, C# — Tags: , , , , , , , — leoullas @ 10:06 pm

static vs. const vs. readOnly static Use of the static modifier to declare a static member, means that the member is no longer tied to a specific object. This means that the member can be accessed without creating an instance of the class. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.
const • Can’t be static. As it is static by default.
• Value is evaluated at compile time.  So, value can’t be changed at runtime.
• Must be initialized as they are declared.
• Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can’t set a constant to a class or structure.
readonly • Can be either instance-level or static.
• Value is evaluated at run time.  So, value can be changed at runtime.
• Can be initialized in declaration or by code in the constructor.
N.B: readonly exists solely to prevent anyone from, either accidentally or intentionally, changing the value of a variable once it’s set. It is enforced at run-time.
const is similar, but enforced at compile-time. Thus, the value must be set at the time the variable is created.

Different types of Parameters in C#

Different types of Parameters in C#: Parameters are means of passing values to a method.
There are four different ways of passing parameters to a method in C#.
1. Value default parameter type in C#.
actual value is passed to the function, which means changes made to the parameter is local to the function and is not passed back to the calling part.
2. Out “out” parameters are output only parameters meaning they can only pass back a value from a function.
3. Ref “ref” parameters are input/output parameters meaning they can be used for passing a value to a function as well as to get back a value from a function.
4. Params “params” parameters is a very useful feature in C#. “params” parameter are used when through a variable number of arguments need to be passed. The “params” should be a single dimensional or a jagged array.
Ref vs. Out //Difference: Ref vs. Out
public void funcRefOut()
int a = 0, b, c = 0, d = 0;//Assigning b = 0 will not make any effect, it should be assigned a value in calling funcd = ParamTest(a, out b, ref c);
richTextBox1.Text = richTextBox1.Text + “\n” + “a = {0} ” + a;
richTextBox1.Text = richTextBox1.Text + “\n” + “b = {0} ” + b;
richTextBox1.Text = richTextBox1.Text + “\n” + “c = {0} ” + c;
richTextBox1.Text = richTextBox1.Text + “\n” + “d = {0} ” + d;
}public static int ParamTest(int a, out int b, ref int c)
a = 10;
b = 20;//Value assign must
c = 30;//Value assign not compulsury
//b = 20;//Error 1 The out parameter ‘b’ must be assigned to before control leaves the current method
//c = 30;// ref type may not be assigned
return 40;
C# Value
Ref Type
.NET uses two different areas of Ram for holding variables;. the stack & heap.
fixed in size when the application is linked Stack [LIFO – bucket]
holds value type variables plus return addresses for functions. All numeric types, ints, floats and doubles along with enums, chars, bools and structs are value types.
basically all unallocated memory. Heap
holds variables created dynamically- known as reference variables and mainly instances of classes(objects) or strings. These variables are stored in two places; there’s a hidden pointer to the place in the heap where the data is stored.
– String
– All arrays, even if their elements are value types
– Class types, such as Form
– DelegatesImportant:
string str = “new string”;//1 address space
str = “modified” + str; //different address and not same address as above
value type is derived from System.ValueType while a reference type is derived from System.Object.
If you assign a value type variable to another then a direct copy of the value is made. But copying a reference type variable just makes a copy of the reference to the variable and does not affect the variable itself.
unlike a value type, a reference type can be null.
implicit conversion vs. explicit conversion 1. Explicit conversions require a cast operator where as an implicit converstion is done automatically.
2. Explicit conversion can lead to data loss where as with implicit conversions there is no data loss.
Will the following code compile?
double d = 9999.11;
int i = d;No, the above code will not compile. Double is a larger data type than integer. An implicit conversion is not done automatically bcos there is a data loss. Hence we have to use explicit conversion as shown below.double d = 9999.11;
int i = (int)d; //Cast double to int.
N.B: InvalidCastException occurs if casting fails
Boxing storing a value type variable in a reference variable
int i = 99;
object t=(object)i;
N.B: boxing happens implicitly
Unboxing storing a reference type variable in a  value type variable
object box = 12;
int i = (int)box;
N.B: – As performance gets impacted, try to avoid boxing and unboxing. In a project where you need boxing and unboxing, use it when it’s absolutely necessary.
– unboxing is an explicit conversion

March 19, 2013

C# .NET Split Function : Inputs – source word and spliter and return – string array

Filed under: All, ASP.NET, C# — leoullas @ 2:36 pm

internal string[] Split(string sourceWord, char[] splitter)
string[] retWords = sourceWord.Split(splitter);
return retWords;

Ping Server from .NET C# Application to check up/down status

Filed under: All, C# — Tags: — leoullas @ 2:33 pm

internal bool PingServer(string IpAddress)
string strDot = “.”;
string[] retWords = Split(IpAddress, strDot.ToCharArray());

bool netOK = false;

byte[] AddrBytes = new byte[] { Convert.ToByte(retWords[0]),
Convert.ToByte(retWords[3]) }; // byte array for server address.

using (System.Net.NetworkInformation.Ping png = new System.Net.NetworkInformation.Ping())
System.Net.IPAddress addr;

addr = new System.Net.IPAddress(AddrBytes);

netOK = (png.Send(addr, 1500, new byte[] { 0, 1, 2, 3 }).Status == IPStatus.Success);
catch (Exception ex)
netOK = false;
return netOK;


internal string[] Split(string sourceWord, char[] splitter)
string[] retWords = sourceWord.Split(splitter);
return retWords;

BackgroundWorker : The basics

Filed under: All, C# — leoullas @ 2:29 pm

1. Add in your Windows form:

Tools -> backgroundWorker1

2. Event: Introduce the activities in the event “backgroundWorker1_DoWork”

In my Start Process GUI button click, I am calling the followings to start the back process.

blStopBackTrackProcess = false;

Then, I have written a non-stop continuous process which is breaking on a boolean value change on my Stop Process GUI button click event.

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

while (1==1){

Thread.Sleep(DRLib.ClConstants.Check_Interval_Second * 1000);
MessageBox.Show(“abcd” );

if (blStopBackTrackProcess == true)

November 20, 2009

Error: The type ‘YourType, YourAssembly’, provided as the Service attribute value in the ServiceHost directive could not be found – Problem while using WCF

Filed under: All, ASP.NET — leoullas @ 4:13 am

Error lied in ServiceIHaveMade.svc file. Need to implement the name change from ‘Service1’ to ‘ServiceIHaveMade’ here too along with the web.config file.

<%@ ServiceHost Language="C#" Debug="true" Service="WcfService_Learn.Service1" CodeBehind="ServiceIHaveMade.svc.cs" %>
<%@ ServiceHost Language="C#" Debug="true" Service="WcfService_Learn.ServiceIHaveMade" CodeBehind="ServiceIHaveMade.svc.cs" %>




              <service name="WcfService_Learn.ServiceIHaveMade" behaviorConfiguration="WcfService_Learn.ServiceIHaveMadeBehavior">

              <!-- Service Endpoints -->

              <endpoint address="" binding="wsHttpBinding" contract="WcfService_Learn.IService1">

              <!-- Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity automatically. -->


                           <dns value="localhost"/>



              <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>





              <behavior name="WcfService_Learn.ServiceIHaveMadeBehavior">

              <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->

                     <serviceMetadata httpGetEnabled="true"/>

                     <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->

                     <serviceDebug includeExceptionDetailInFaults="false"/>





November 3, 2009


Filed under: All, ASP.NET, C# — leoullas @ 8:55 am

Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:


// Declare the generic class
public class GenericList<T>
    void Add(T input) { }
class TestGenericList
    private class ExampleClass { }
    static void Main()
        // Declare a list of type int
        GenericList<int> list1 = new GenericList<int>();

        // Declare a list of type string
        GenericList<string> list2 = new GenericList<string>();

        // Declare a list of type ExampleClass
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
  • Use generic types to maximize code reuse, type safety, and performance.
  • The most common use of generics is to create collection classes.
  • The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.
  • You can create your own generic interfaces, classes, methods, events and delegates.
  • Generic classes may be constrained to enable access to methods on particular data types.
  • Information on the types used in a generic data type may be obtained at run-time by means of reflection.

//For Interfaces
interface IComparable <T>
//for structs
struct HashBucket <K,D>
//for methods
static void Reverse <T> (T[] arr)
//for delegates
delegate void Action <T> (T arg)

Strongly TYPED & Loosely TYPED

Filed under: All, ASP.NET, C# — leoullas @ 8:49 am

Definition: A strongly typed programming languages is one that requires the type of a variable to be explicitly stated. C is a strongly typed language. You must declare the type of data a variable will store for C to interpret it:

int myVariable;
myVariable = 25;

Perl is a loosely typed language. There is no need to declare the variable type before using it:

$myVariable = 25;
$myVariable = “A String.”;

Basic dode to fetch data from sql server using select statement and put it in dataset using dataadapter

Filed under: All, ASP.NET, C# — leoullas @ 8:42 am

System.Data.SqlClient.SqlConnection objConnection;

System.Data.DataSet objDataSet = new DataSet();

System.Data.SqlClient.SqlDataAdapter objDataAdapter;

objConnection = new SqlConnection("data source=; uid= tallyman; pwd= tallyman; database=Tallyman");

#region Either of these 2 works

//objDataAdapter = new SqlDataAdapter("Select top 5 id from accounts", "data source=; uid= tallyman; pwd= tallyman; database=Tallyman");

objDataAdapter = new SqlDataAdapter("Select top 5 id from accounts", objConnection);

#endregion Either of these 2 works

objDataAdapter.Fill(objDataSet, "accountsData");



October 28, 2009

DropDown List With HardCoded Values with Default Selected a value

Filed under: All, ASP.NET, C# — leoullas @ 10:41 am

There are two ways:


Way 1:

In aspx file:

     <td style=”width: 90px; height: 56px;” valign=”middle”>

        <asp:DropDownList ID=”ddlTime” runat=”server” Width=”131px” onchange=”clickClient();”  Height=”19px”>



In aspx.CS file:

    public static void PopulateDdlTime(DropDownList ddlTime)


        ddlTime.Items.Add(new ListItem(“12:00AM–08:00AM”, “1200AM0800AM”));

        ddlTime.Items.Add(new ListItem(“08:00AM–04:00PM”, “0800AM0400PM”));

        ddlTime.Items.Add(new ListItem(DRISInternatiolization.DRISInternatiolization.GetLabelText(“464”), “Customize”));

        ddlTime.SelectedValue = “0800AM0400PM”;


protected void Page_Load(object sender, EventArgs e)






Way 2:

In aspx file:

<td style=”width: 90px; height: 56px;” valign=”middle”>

    <asp:DropDownList ID=”ddlTime” runat=”server” Width=”131px” onchange=”clickClient();” Height=”19px”>

                  <asp:ListItem Value=”1200AM0800AM”>12:00AM–08:00AM</asp:ListItem>

                  <asp:ListItem Value=”0800AM0400PM” Selected=”True”>08:00AM–04:00PM</asp:ListItem>

                  <asp:ListItem Value=”Customize”>Customize…</asp:ListItem>



Older Posts »

Create a free website or blog at WordPress.com.

%d bloggers like this: