Struct – Code:
using System;
class Test {
int classvar ;
int anothervar =20;
public Test ( )
{
classvar = 28;
}
public static void Main()
{
Test t = new Test();
ExampleStruct strct = new ExampleStruct(20);
System.Console.WriteLine(strct.i);
strct.i = 10;
System.Console.WriteLine(t.classvar);
System.Console.WriteLine(strct.i);
strct.trialMethod();
}
}
struct ExampleStruct {
public int i;
public ExampleStruct(int j)
{
i = j;
}
public void trialMethod()
{
System.Console.WriteLine("Inside Trial Method");
}
}
O/P:-
28
20
10
Inside Trial Method
In the above example, I have declared and used a constructor with a single parameter for
In the above example, I have declared and used a constructor with a single parameter for
a structure. Instead if I had tried to use a default parameter-less parameter I would have
got an error. But the same is possible in the case of classes as shown by the default
parameter-less constructor, which initializes the classvar variable to 28.
Another point to note is that a variable called anothervar has been declared and initialized
within the class whereas the same cannot be done for members of a structure.
No comments:
Post a Comment