Showing posts with label OOPS. Show all posts
Showing posts with label OOPS. Show all posts

Tuesday, March 23, 2010

Struct


  1. Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
     
    //public int UserId = 10; //Error

  2. A struct may not declare a default constructor (a constructor without parameters) or a destructor. Any private or otherwise inaccessible members can be initialized only in a constructor.
  3. Copy a struct to struct.
    If you copy a struct, C# creates a new copy of the object and assigns the copy of the object to a separate struct instance.
    Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. This is important to remember when working with collections of value types such as Dictionary.
     
    Student s1 = new Student();
    Student s2;
    s1 = s2;
    Response.Write(s1.PUserId);
    Response.Write(s2.PUserId);

    Here all the values of s1 will be copied to s2.
  4. Structs are value types and classes are reference types.
  5. Unlike classes, structs can be instantiated without using a new operator.
     
    Student s1;
    s1.Address = "Savadipalayam";

  6. Initialize the fields through properties. Use of unassigned local variable 's1'.
     
    Student s1;
    Response.Write(s1.PUserId)

    In fact, when instantiating a struct without the new keyword, we must first initialize its fields explicitly.
     
    Student s1;
    s1.PUserId = 10;
    Response.Write(s1.PUserId)

  7. Structs can declare constructors that have parameters. But all the field variables should be fully initialzed.
     
    public Student(int UserId, int ZipCode, double Salary, string Address)
    {
    this.UserId = UserId;
    this.ZipCode = ZipCode;
    this.Salary = Salary;
    //this.Address = Address;
    }

    This will produce an error Field 'StructTest.Student.Address' must be fully assigned before control is returned to the caller". Since Address is not initialized.
  8. A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.
  9. A struct can implement interfaces, and it does that exactly as classes do.
  10. Cannot convert null to 'StructTest.Student'

    Student s2 = null;

    DateTime is struct. We can't assign null to DateTime.
    Cannot convert null to 'System.DateTime' because it is a non-nullable value type.
    eg.

    DateTime dt = null;

  11. A struct can be used as a nullable type and can be assigned a null value.
    Working with Nullable Types in struct.
  12. If a field is not initialized whether it is a primitive data type it produce the error "Use of possibly unassigned field 'i'" when we didn’t create instance for the struct.

    Student1 s3;
    Response.Write(s3.i);


  13. When we create an instance for the struct but we don’t have any constructor to assing value, it will asign the default value for premitive datatype and for others it will assing null(null for string).


    public struct Student1
    {
    public int i;
    public string j;
    }

    Student1 s3 = new Student1();
    Response.Write(s3.i); //O/P = 0
    Response.Write(s3.j); //O/P = null


  14. struct can also have copy constructor but have to be fully initialzed.

    public Student(Student stud)
    {
    this.UserId = stud.UserId;
    this.ZipCode = stud.ZipCode;
    this.Salary = stud.Salary;

    //Field 'StructTest.Student.Address' must be fully assigned before control is returned to the caller
    //this.Address = stud.Address;

    this.Address = stud.Address;
    }

  15. Struct can contain methods. It may be static, and a static method can call only another static methods.

    public void sub()
    {

    }

    public static string multiply()
    {
    return Send();
    }

    public static string Send()
    {
    //An object reference is required for the non-static field, method, or property 'StructTest.Student.Address'
    //Address = "Mottur Road";
    //return Address;

    Street = "Mottur Road";
    return Street;
    }

  16. //The allowed modifiers are new, static, virtual, override, and a valid combination of the four access modifiers (public, internal and private).

    // Override the ToString method so the value appears in text
    public override string ToString()
    {
    return String.Format("({0},{1})", Street, Address);
    }

  17. Support access modifiers, constructors, indexers, methods, fields, nested types, operators, and properties.

    public int PUserId
    {
    get { return UserId; }
    set { UserId = value; }
    }

  18. Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal.. If we declare a struct inside a namespace with any of the access specifier as private, protected, or protected internal, we will get this error.
    So it is always public when we declare a struct inside a namespace.
  19. Abstract and sealed modifiers are not permitted in a struct declaration since it is always implicitly sealed.
    Since it is implicitly sealed, struct members may not be declared protected.
    So we can't able to inherit another struct.
    Since it is not abstract, struct can't be a base to a class or another structure.



struct Student : IOne, ITwo
{
int UserId;
//public int UserId = 10; //Within a struct declaration, fields cannot be initialized unless they are declared as const or static.

public static string Street = "Savadipalayam";

int ZipCode;
double Salary;
public string Address;

//Structs cannot contain explicit parameterless constructors(Default constructor)
/* public Student()
{
this.UserId = 10;
this.ZipCode = 637101;
this.Salary = 2000;
this.Address = "Idappadi";
}
*/

// all the members of the struct has to be initialized in this way
public Student(int UserId, int ZipCode, double Salary, string Address)
{
this.UserId = UserId;
this.ZipCode = ZipCode;
this.Salary = Salary;
this.Address = Address;
}

// struct can also have copy constructor but have to be fully initialzed
public Student(Student stud)
{
this.UserId = stud.UserId;
this.ZipCode = stud.ZipCode;
this.Salary = stud.Salary;

//Field 'StructTest.Student.Address' must be fully assigned before control is returned to the caller
//this.Address = stud.Address;

this.Address = stud.Address;
}

public int PUserId
{
get { return UserId; }
set { UserId = value; }
}

//new protected member declared in struct
//protected void add()
//{
//}

//Struct can contain methods. It may be static, and can call only another static methods.
public void sub()
{

}

public static string multiply()
{
return Send();
}

public static string Send()
{
//An object reference is required for the non-static field, method, or property 'StructTest.Student.Address'
//Address = "Mottur Road";
//return Address;

Street = "Mottur Road";
return Street;
}

//The modifier 'abstract' is not valid for this item
//public abstract void Return() { }

#region ITwo Members

void ITwo.add()
{
throw new System.NotImplementedException();
}

public void sum()
{
throw new System.NotImplementedException();
}

#endregion

#region IOne Members

void IOne.add()
{
throw new System.NotImplementedException();
}

void IOne.sum()
{
throw new System.NotImplementedException();
}

#endregion
}

//Nested Structures


public struct outer
{
public int i;
public struct inner
{
public int j;
}
}


How to call?.


outer.inner inn = new outer.inner();
inn.j = 10;


References
C# School
vijaymukhi
C# Online.net
codeproject
csharp-station

Monday, January 11, 2010

Static

Static variables are called Class Fields
Static methods are called Class Members
Not static fields are called instance fields or members

What are the things that we can declare as static?
1.data fields
2.member functions
3.properties
4.events

CLASS
A C# class can contain both static and non-static members. When we declare a member with the help of the keyword static, it becomes a static member.

A static member belongs to the class rather than to the objects of the class. Hence static members are also known as class members and non-static members are known as instance members.

In C#, data fields, member functions, properties and events can be declared either as static or non-static. Remember that indexers in C# can't declare as static.

Static classes cannot be instantiated. (I.e. creating an object). If we try to create an object we will get the error, Cannot create an instance of the abstract class or interface 'StaticClassName'

When a class is declared to as static, it is sealed, abstract, and no instance members can be overridden or declared. A static class contains only static members

Since static classes are sealed so they cannot be inherited.

Advantage
No need to create instance.
When to use static class?
Suppose we are using certain methods or properties often we can just call them without creating instance.
It contains only the last updated value. The updated value reflects to all the users.
Static classes can be used when there is no data or behavior in the class that depends on object identity.

static class A
{
static void Foo()
{

A x = null as A; // Cannot declare a variable of static type 'A'
A a; // Cannot declare a variable of static type 'A'
a = new A(); // Cannot create an instance of the static class 'A'

}
}

Static Fields
Static fields can be declared as follows by using the keyword static.
class MyClass
{
public static int x;
public static int y = 20;
}
When we declare a static field inside a class, it can be initialized with a value as shown above.

The static field for a class executes at most once in a given application domain (i.e. when we keep the breakpoint both at a static and non static field and when we refresh the page, the non static field executes but static field didn't). But the value can be changed later in the constructor or anywhere. The last updated value will be maintained there after.

All un-initialized static fields automatically get initialized to their default values when the class is loaded first time.

The C# provides a special type of constructor known as static constructor to initialize the static data members when the class is loaded at first.
// C# static constructor
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int x;
public static int y;
static MyClass()
{
x = 100;
Y = 200;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y);
}
}
Constructor:
Note that static constructor is called when the class is loaded at the first time. However, we can't predict the exact time and order of static constructor execution.

They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class is called.

Static class can't have instance constructor. (Since we can’t able to instantiate a static class)

A static constructor must be parameter less. (That means there is only one form of static constructor, without any parameters. In other way it is not possible to overload a static constructor).

There is no access modifier require defining a static constructor.

The static constructor for a class executes at most once in a given application domain (i.e. Static constructors are used to perform a particular action that needs performed once only.) The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

1. An instance of the class is created.
2. Any of the static members of the class are referenced.


Static constructor called before the class is referenced for the first time in your program.
It contains only static variables.

Static constructors can't access non-static data members directly.

(A non-static class can have static constructor. When creating instance the static constructor will be called first. Here also the constructor will be called only once till we restart web server.)

Member Functions
Only static members are allowed inside a static class. (I.e. if a class is declared as static all the fields, members should be static.)

We can invoke a static member only through the name of the class.

But a static member function can access only other static members. (I.e. if a member is declared as static all the fields should be static and the method that we are calling from (the caller method) should be static.)
We can’t able to declare a variable as static inside a static method.

An object reference is required for the non-static field, method, or property.

public class foo
{

int x;

static void doSomthingWithX()
{

Console.Write(x.toString);

}
}


Member modifier 'static' must precede the member type and name

void static doSomthingWithX()

Static classes cannot have instance constructors

Cannot declare instance members in a static class

public static partial class StaticClassTest
{

//Static classes cannot have instance constructors
StaticClassTest()
{
}

//cannot declare instance members in a static class
int j = 10;


static int i = 10;

public static int ClassMethod()
{

//The modifier 'static' is not valid for this item
//static int k = 10;

int k = 10;
return i;

return i;
}

//'InstanceMethod': cannot declare instance members in a static class
public int InstanceMethod()
{
return 8;
}

}

The modifier 'static' is not valid for this item
private static void StaticTest()
{
static int i;
i =10;

}

Solution
Whatever we declare inside static method, it is static by default.. So no need to declare a variable as static in static method.

Static Properties
The properties also can be declared as static. The static properties are accessing using the class name. All the rules applicable to a static member are applicable to static properties.
public class PropertyClass
{
private static int x;
public static int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
PropertyClass.X = 10; // calls setter
int value = PropertyClass.X; // calls getter
}
Remember that set/get accessor of static property can access only other static members of the class. Also static properties are invoking by using the class name.

Static Members & Inheritance
A derived class can inherit a static member.

But a static member in C# can't be marked as override, virtual or abstract.

However it is possible to hide a base class static method in a derived class by using the keyword new.
public class BaseClassTest
{
public static int i = 10;
public static int get()
{
return i;
}
}

public class ChildClassTest : BaseClassTest
{
public static int j;

//ChildClassTest()
//{
// //cannot be accessed with an instance reference; qualify it with a type name instead
// j = base.i;
//}

//static ChildClassTest()
//{
// //Keyword 'base' is not available in a static method
// j = base.i;
//}

}
class Final : ChildClassTest
{
int p = ChildClassTest.i;
int o = ChildClassTest.get();
int r = ChildClassTest.j;
}

class tester
{
int p = Final.i;
int o = Final.get();
int r = Final.j;
}
Finally remember that it is not possible to use this to reference static methods.
Static Indexers
In C# there is no concept of static indexers, even though static properties are there.
http://www.c-sharpcorner.com/UploadFile/rajeshvs/PropertiesInCS11122005001040AM/PropertiesInCS.aspx

http://www.csharphelp.com/2006/04/c-static-members/