Wednesday, September 29, 2010

Passing parameters with 'Val', 'Ref', 'Out'


Passing ValueType Parameters:

passing a value-type variable to a method means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the variable. If you want the called method to change the value of the parameter, you have to pass it by reference, using the ref or out keyword. For simplicity, the following examples use ref.
  • Passing value types by value
  • Passing value types by reference
Passing value types by value:
The following example demonstrates passing value-type parameters by value. The variables Var1 and Var2 are passed by value to the method MyFunction. Any changes that take place inside the method have no affect on the original value of the variable.

Example1:
Take a windows application and add a button in the form.

int Var1 = 10;
int Var2 = 20;

private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Values in 'Var1' and 'Var2' Before calling the method : " + Var1.ToString() + " " + Var2.ToString());
MyFunction(Var1 , Var2 );
MessageBox.Show("Values in 'Var1' and 'Var2' After calling the method :" + Var1.ToString() + " " + Var2.ToString());
}

private void MyFunction(int a, int b)
{
a = 101;
b = 201;
MessageBox.Show("Values in 'Var1' and 'Var2' INSIDE the method :" + a.ToString() + " " + b.ToString());
}

Output:
Values in 'Var1' and 'Var2' Before calling the method : 10 20
Values in 'Var1' and 'Var2' INSIDE the method : 101 201
Values in 'Var1' and 'Var2' After calling the method : 10 20

Passing Value Types by Reference:
The following example is the same as Example 1, except for passing the parameter using the ref keyword. The value of the parameter is changed after calling the method.

Example2:
Take a windows application and add a button in the form.

int Var1 = 10;
int Var2 = 20;

private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Values in 'Var1' and 'Var2' Before calling the method : " + Var1.ToString() + " " + Var2.ToString());
MyFunction(
ref Var1 , ref Var2 );
MessageBox.Show("Values in 'Var1' and 'Var2' After calling the method :" + Var1.ToString() + " " + Var2.ToString());
}

private void MyFunction(ref int a, ref int b)
{
a = 101;
b = 201;
MessageBox.Show("Values in 'Var1' and 'Var2' INSIDE the method :" + a.ToString() + " " + b.ToString());
}

Output:
Values in 'Var1' and 'Var2' Before calling the method : 10 20
Values in 'Var1' and 'Var2' INSIDE the method : 101 201
Values in 'Var1' and 'Var2' After calling the method : 101 201

Passing Reference Type Parameters:

Passing Reference Types By Value:
The following example demonstrates passing a reference-type parameter, MyArr, by value, to a method, 'MyFunction'. Because the parameter is a reference to MyArr, it is possible to change the values of the array elements. However, the attempt to reassign the parameter to a different memory location only works inside the method and does not affect the original variable, MyArr.

Example3:
Take a windows application and add a button in the form.

private void button1_Click(object sender, EventArgs e)
{
int[] MyArr = {10,20,30};
MessageBox.Show("Value in 'MyArr[0]' Before calling the method : " + MyArr[0].ToString() );
MyFunction(
MyArr );
MessageBox.Show("Value in
'MyArr[0]' After calling the method :" +MyArr[0].ToString() );
}

private void MyFunction(
int[] a)
{
a[0] = 875; //this change afftets the original
a=new int[]{-12,-13,-14,-15,-17}; //this change is local
MessageBox.Show("Value in
'MyArr[0]' INSIDE the method :" + a[0].ToString() );
}

Output:
Value in 'MyArr[0]' Before calling the method : 10
Value in 'MyArr[0]' INSIDE the method : -12
Value in 'MyArr[0]' After calling the method : 875

Passing Reference Types By Reference:
This example is the same as Example 3, except for using the ref keyword in the method header and call. Any changes that take place in the method will affect the original variables in the calling program.

Example4:
Take a windows application and add a button in the form.

private void button1_Click(object sender, EventArgs e)
{
int[] MyArr = {10,20,30};
MessageBox.Show("Value in 'MyArr[0]' Before calling the method : " + MyArr[0].ToString() );
MyFunction(
ref MyArr );
MessageBox.Show("Value in
'MyArr[0]' After calling the method :" +MyArr[0].ToString() );
}

private void MyFunction(ref
int[] a)
{

//Both of the following will affect the original value.
a[0] = 875;
a=new int[]{-12,-13,-14,-15,-17};
MessageBox.Show("Value in
'MyArr[0]' INSIDE the method :" + a[0].ToString() );
}

Output:
Value in'MyArr[0]' Before calling the method : 10
Value in 'MyArr[0]' INSIDE the method : -12
Value in'MyArr[0]' After calling the method : -12

Difference between 'Ref' and 'Out'
:

ref requires that the variable be initialized before being passed, where as out need not be initialized before being passed.

The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument

Declaring an out method is useful when you want a method to return multiple values. A method that uses an out parameter can still return a value. A method can have more than one out parameter.

An overload will occur if declarations of two methods differ only in their use of ref. However, it is not possible to define an overload that only differs by ref and out. For example, the following overload declarations are valid:
class MyClass
{
public void MyMethod(int i)
{i = 10;}
public void MyMethod(ref int i)
{i = 10;}
}

but the following overload declarations are invalid:
class MyClass
{
public void MyMethod(out int i)
{i = 10;}
public void MyMethod(ref int i)
{i = 10;}
}

Monday, September 27, 2010

Difference b/w Stored Proc and Function

1) a) Stored Procedure may or may not return values. i.e if insert statements are present in the sp then it wont return anything. If select
statement is within sp then return a table.
b) A User Defined Function should return values

2) a) SP may have input and output parameters
b) UDF can have only input parameters

3) a) All DML operations can be done withing SP.
b) Only Select operation can be done in UDF

4) a) SP cannot be used with select/where/having cluases.
b) UDF can be used with select/where/having cluases.

5) a) SP can call a UDF
b) UDF cannot call a SP

6) a) SP can be run independently using EXEC
b) UDF cannot run independently

7) a) Temporary tables can be created in SP.
b) Temporary tables cannot be created in UDF.

Sunday, September 26, 2010

Questions asked in Prokarma

What is 'internal'?

What is difference between inheritance and abstract class?
(My fuse is off after listening this question...I dont think this is a meaningful question.....I dont know what interviewer's intention to ask that)

What is a Static class?

What script manager does?
The ScriptManager control manages client script for AJAX-enabled ASP.NET Web pages. By default, the ScriptManager control registers the script for the Microsoft Ajax Library with the page. This enables client script to use the type system extensions and to support features such as partial-page rendering and Web-service calls

Where did you use Webservice in your project?

What is the difference between Primary key and Unique key?
  • Primary Key..
1.It will not accept null values.
2.There will be only one primary key in a table.
3.Clustered index is created in Primary key.
4.Primary key allows each row in a table to be uniquely identified and ensures that no duplicate rows exist.

  • Unique Key..
1.Null values are accepted.
2.More than one unique key will be there in a table.
3.Non-Clustered index is created in unique key.
4.Unique key constraint is used to prevent the duplication of key values within the rows of a table and allow null values.

What is the difference between Stored Procedure and User defined function?

What are the extra controls provided in .net 3.5 over .net 2.o?
A) ListView
DataPager
Ajax Extension Controls like scriptmangaer, updatepanel...etc.

Questions asked in Nihelient

1)what are partial class?

It is possible to split the definition of a class or struct or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled( means a single dll is formed for all the partial class files with same name when compiled).


2)can two partialclasses have same method?

No...Two partial classes should not have same methods. The following code gives a Compile Error...

public partial class MyClass
{
private int Total = 0;

public void MyMethod()
{
}
}
public partial class MyClass
{
private string EmpName = "";

public void MyMethod()
{

}
}
3)what is application pooling?

Concept of Application pool has from IIS 6.0


if you want to isolate all the Web applications running in the same computer, you can do this by creating a separate application pool for every Web application and placing them in their corresponding application pool.
Because each application pool runs in its own worker process, errors in one application pool will not affect the applications running in other application pools. Deploying applications in application pools is a primary advantage of running IIS 6.0 in worker process isolation mode because you can customize the application pools to achieve the degree of application isolation that you need.



4)what is the diff between normal page life cycle and page life cycle
having master pages?


The following is the sequence in which events occur when a master page is merged with a content page:
  1. Master page controls Init event.
  2. Content controls Init event.
  3. Master page Init event.
  4. Content page Init event.

  5. Content page Load event.
  6. Master page Load event.
  7. Content controls Load event.

  8. Content page PreRender event.
  9. Master page PreRender event.
  10. Master page controls PreRender event.
  11. Content controls PreRender event.

http://msdn.microsoft.com/en-us/library/dct97kc3(v=vs.80).aspx

5)what is virtual directory?how many we can creat in a appliction?

6) waht do u mean by delete & truncate?

7)cann we use views for update, insert and delete?

Views in all versions of SQL Server are updatable (can be the target of UPDATE, DELETE, or INSERT statements), as long as the modification affects only one of the base tables referenced by the view.


http://www.codeproject.com/KB/database/View.aspx


8)diff between string and string builder?

9)Diff between hash table and Array List?

10)waht is array List?

11)what is static class ? why do u use them?

12)what is column label in sql?

13)what are the type of indexes?

14)how many no of indexs will be present for a table?

15)what doo u mean by cascading delete?

16)What do u mean by serialization?

17)what do u mean by sessions?

18)what do umean by cokkies?

19)waht are the types of authentication?

20)where does the authentication credentials save in the web application?

21)what are char and nchar?

CHAR and NCHAR data types are both character data types that are fixed-length. 


CHAR holds only non-unicode character so it needs one byte for storing a character.


NCHAR holds Uni-code character which needs two bytes for storing one character.

22)what are varchar and nvarchar?


VARCHAR and NVARCHAR data types are both character data types that are variable-length. 

VARCHAR holds only non-unicode characters so it needs one byte for storing a character.

NVARCHAR holds Uni-code characters which needs two bytes for storing one character.


23)what do u mean by virtual? and can we override without that?

No...

24)what do u mean by strongname and what does it contain?

25)diff between .Exe and .Dll ?

26)can we place a .Exe in GAC?

27)what do u mean by Delegates?

28)what do u mean by multicast Delegate?

Tuesday, September 21, 2010

Main() method in C#

  • The Main method is the entry point of your program, where the program control starts and ends.


class TestClass
{ static void Main(string[] args)
{ // Display the number of command line arguments:
System.Console.WriteLine(args.Length);
}
}
  • It is declared inside a class or struct. It must be static and it should not be public. (In the example above it receives the default access of private.)

  • It can either have a void or int return type.

  • The Main method can be declared with or without parameters.

  • Parameters can be read as zero-indexed command line arguments.

Source:msdn

Exception Handling in C#


Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.


C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process.

The general form try-catch-finally in C# is shown below

try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}

If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block.

But in C#, both catch and finally blocks are optional(one of them must be present with try). The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.

If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.

In C#, exceptions are nothing but objects of the type Exception. The 'Exception' is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc.

Uncaught Exceptions

The following program will compile but will show an error during execution. The division by zero is a runtime anomaly and program terminates with an error message. Any uncaught exceptions in the current context propagate to a higher context and looks for an appropriate catch block to handle it. If it can't find any suitable catch blocks, the default mechanism of the .NET runtime will terminate the execution of the entire program.

//C#: Exception Handling
//Author: rajeshvs@msn.com
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 100/x;
Console.WriteLine(div);
}
}

The modified form of the above program with exception handling mechanism is as follows. Here we are using the object of the standard exception class DivideByZeroException to handle the exception caused by division by zero.

//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("This line in not executed");
}
catch(DivideByZeroException de)
{
Console.WriteLine("Exception occured");
}
Console.WriteLine("Result is {0}",div);
}
}

In the above case the program do not terminate unexpectedly. Instead the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements.
If a finally block is present, the code inside the finally block will get also be executed.

//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{
Console.WriteLine("Exception occured");
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}

Remember that in C#, the catch block is optional. The following program is perfectly legal in C#.

//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}

But in this case, since there is no exception handling catch block, the execution will get terminated. But before the termination of the program statements inside the finally block will get executed. In C#, a try block must be followed by either a catch or finally block.

Multiple Catch Blocks

A try block can throw multiple exceptions, which can handle by using multiple catch blocks. Remember that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error.

//C#: Exception Handling: Multiple catch
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{
Console.WriteLine("DivideByZeroException" );
}
catch(Exception ee)
{
Console.WriteLine("Exception" );
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}

Catching all Exceptions

By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class.

//C#: Exception Handling: Handling all exceptions
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch
{
Console.WriteLine("oException" );
}
Console.WriteLine("Result is {0}",div);
}
}

The following program handles all exception with Exception object.

//C#: Exception Handling: Handling all exceptions
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(Exception e)
{
Console.WriteLine("oException" );
}
Console.WriteLine("Result is {0}",div);
}
}

Throwing an Exception

In C#, it is possible to throw an exception programmatically. The throw keyword is used for this purpose. The general form of throwing an exception is as follows.

throw exception_obj;

For example the following statement throw an ArgumentException explicitly.

throw new ArgumentException("Exception");

//C#: Exception Handling:
using System;
class MyClient
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception" );
}
Console.WriteLine("LAST STATEMENT");
}
}

Re-throwing an Exception

The exceptions, which we caught inside a catch block, can re-throw to a higher context by using the keyword throw inside the catch block. The following program shows how to do this.

//C#: Exception Handling: Handling all exceptions
using System;
class MyClass
{
public void Method()
{
try
{
int x = 0;
int sum = 100/x;
}
catch(DivideByZeroException e)
{
throw;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
try
{
mc.Method();
}
catch(Exception e)
{
Console.WriteLine("Exception caught here" );
}
Console.WriteLine("LAST STATEMENT");
}
}

Standard Exceptions

There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System.Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include IOException, WebException etc.

The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications.


  • System.OutOfMemoryException
  • System.NullReferenceException
  • Syste.InvalidCastException
  • Syste.ArrayTypeMismatchException
  • System.IndexOutOfRangeException
  • System.ArithmeticException
  • System.DevideByZeroException
  • System.OverFlowException
User-defined Exceptions

In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in C#. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes.

//C#: Exception Handling: User defined exceptions
using System;
class MyException : Exception
{
public MyException(string str)
{
Console.WriteLine("User defined exception");
}
}
class MyClient
{
public static void Main()
{
try
{
throw new MyException("RAJESH");
}
catch(Exception e)
{
Console.WriteLine("Exception caught here" + e.ToString());
}
Console.WriteLine("LAST STATEMENT");
}
}

Note: Article taken from www.c-charpcorner.com All credits goes to author Rajesh VS.

Monday, September 20, 2010

Indexers & Properties

Indexers And Properties In C#

System.Collections ( Array List )

ArrayList

The ArrayList class is a dynamic array of heterogeneous objects. In an ArrayList, however, we can have different type of objects; these in turn would be stored as object type only.

We can have an ArrayList object that stores integer, float, string, etc., but all these objects would only be stored as object type.

An ArrayList uses its indexes to refer to a particular object stored in its collection.

The Count property gives the total number of items stored in the ArrayList object.

The Capacity property gets or sets the number of items that the ArrayList object can contain.

Objects are added using the Add() method of the ArrayList and removed using its Remove() method.

( heterogeneous - Consisting of elements that are not of the same kind )

An example of usage of an ArrayList is given below.

int a =4;

double b =5.6;

ArrayList ObjArrLst = new ArrayList();

ObjArrLst.Add("Cricket");

ObjArrLst.Add(a);

ObjArrLst.Add(b);

It is to be noted here that the initial capacity of an ArrayList is 16, which is increased once the 17th item is stored onto it. This repeated memory allocation and copying of the items can be quite expensive in some situations.

For performance reasons we can set the initial capacity of the object of an ArrayList by using the Capacity property of the ArrayList class. This is shown in the example below.

int a =4;

double b =5.6;

ArrayList ObjArrLst = new ArrayList();

ObjArrLst.Capacity =3;

ObjArrLst.Add("Cricket");

ObjArrLst.Add(a);

ObjArrLst.Add(b);

Other methods available with Array List Class are

ClearRemoves all elements from the ArrayList.
Public methodCloneCreates a shallow copy of the ArrayList.
Public methodContainsDetermines whether an element is in the ArrayList.

InsertInserts an element into the ArrayList at the specified index.

RemoveRemoves the first occurrence of a specific object from the ArrayList.
Public methodRemoveAtRemoves the element at the specified index of the ArrayList.

ReverseReverses the order of the elements in the entire ArrayList.

SortSorts the elements in the entire ArrayList.

ToArrayCopies the elements of the ArrayList to a new Object array.

TrimToSizeSets the capacity to the actual number of elements in the ArrayList.

Sunday, September 19, 2010

Constructor

Constructor is a method in a Class which is executed or Called as soon as an object is created for that Class.

In VB.NET, Constructor always named as 'New' and is a sub procedure.
In C#, Constructor name is same as Class Name and does'nt have a return type not even void.

Constructor with no parameters is called Default Constructor and the one with parameters is called Parametrized Constructor.

Copy Constructor is used to copy data members of the existing object to new object data members.





In VB.NET,

Public Sub New() 'Default Constructor

End Sub

public Sub New(ByVal id as integer, ByVal Name as string)
Me.New() 'Calling Default Constructor first..
'this is Parametrized Constructor..
End Sub

In C#,

Public Class Account
{
Public Account() //Construtor name same as class name...
{
//Default Constructor..
}

Public Account(int id, String name) : this()
{
//Parameterized Constructor...
}
}


From the above table, it is clear that constructors can be overloaded.

Saturday, September 18, 2010

Singleton Class

A Class that can be instantiated only once is called Singleton Class. i.e We can create only one object for a Singleton class.

Constructor in a Singleton Class has to be made private so that object cannot be created outside the class.

public Class SingleTonDemo
{
private SingleTonDemo // Note that Constructor is made Private.
{
}
public Static SingleTonDemo Obj;
public int a;
//create a property which gives the only created object..
public Static SingleTonDemo GetOnlyObject
{
if(Obj==null)
{
Obj = new SingleTonDemo();
return Obj;
}
}
} //end of the class

SingleTonDemo Ref1;
SingleTonDemo Ref2;

Ref1=SingleTonDemo.GetOnlyObject;
Ref2=SingleTonDemo.GetOnlyObject;

Ref1.a=10;

Console.Writeline(Ref2.a);

//Output 10...since the both Ref1 and Ref2 referencing to the same object.


http://msdn.microsoft.com/en-us/library/ff650316.aspx

Static Class and Static/Shared members

Statc ( C# ) / Shared ( VB.NET )

Static Class :

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example:

UtilityClass.MethodA();

The following list provides the main features of a static class:

  • Contains only static members.

  • Cannot be instantiated.

  • Is sealed. ( therefore static class cannot be inherited )

  • Cannot contain Instance Constructors. ( however, they can contain a static constructor.)


a static class remains in memory for the lifetime of the application domain in which your program resides.

When to use Static Class: A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields.
For example, in the .NET Framework Class Library, the static System.Math class contains several methods that perform mathematical operations, without any requirement to store or retrieve data that is unique to a particular instance of the Math class.

Note: Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

Advantage of Static Class:

public static class MyCalc
{

static MyCalc()
{

}

MyCalc obj = new MyCalc(); //compiler wont allow you to create this...it will show error...

}
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Here is an example of a static class that contains two methods that convert temperature from Celsius to Fahrenheit and from Fahrenheit to Celsius:

public static class TemperatureConverter {

public static double CelsiusToFahrenheit(string temperatureCelsius)
{ // Convert argument to double for calculations.
double celsius = Double.Parse(temperatureCelsius);
// Convert Celsius to Fahrenheit.

double fahrenheit = (celsius * 9 / 5) + 32;

return fahrenheit;
}

public static double FahrenheitToCelsius(string temperatureFahrenheit)
{ // Convert argument to double for calculations.
double fahrenheit = Double.Parse(temperatureFahrenheit);
// Convert Fahrenheit to Celsius.
double
celsius = (fahrenheit - 32) * 5 / 9;

return celsius;
}

}

Calling static methods...

TemperatureConverter.CelsiusToFahrenheit(12);

TemperatureConverter.FahrenheitToCelsius(13);
---------------------------------------------------------------------------------------------------
Static/Shared members :

Static / Shared variables declared in a class are shared among all the objects that are created for a Class.

For every new object is created for a Class, all the members of the Class are allocated memory. But Static / Shared members of the Class are allocated memory only once irrespective of number of objects created.

Memory for Static / Shared member is allocated when Class is loaded.

A Class is loaded when first instance(Object) is created.

These members are also called as Class members and are accessed outside the class using the Class name.

public class MyClass
{
public static int a;
}
MyClass.a = 10;

Two common uses of static fields are
  • to keep a count of the number of objects that have been instantiated, or
  • to store a value that must be shared among all instances.
Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.

A const field is essentially static in its behavior.

Note : C# does not support static local variables (variables that are declared in method scope)

If your class contains static fields, provide a static constructor that initializes them when the class is loaded.

---------------------------------------------------------------------------------------------------

Static/Shared Constructor :

1. Static/Shared Constructor is executed by CLR when Class is loaded. So this is used to initialize Static/Shared members dynamically.

2. Static Constructor cannot be overloaded ( Normal constructor can be overloaded )

3. Static Constructor has no access specifiers like private/public.

Series of events that occur when the first object is created for a Class .....

* Class is loaded
* Static members are loaded and allocated memory.
* Static Constructor is called.
* Normal members are loaded and allocated memory.
* Normal Constructor is called.

Observe the above series.....Point to be noted is you cannot access normal members of a class in Static Constructor as they are loaded after Static Constructor is executed.


A Class in C# can be declared as Static. Such a Class should has static members only. This is not supported in VB.NET.

-------------------------------------------------------------------------------------------------