Beruflich Dokumente
Kultur Dokumente
A constructor is a member function that has the same name as the class name and is invoked
automatically when the class is instantiated. A constructor is used to provide initialization code
that gets executed every time the class is instantiated.
Points to be noted on constructors:
• Constructors cannot be "virtual". They cannot be inherited.
• Constructors are called in the order of inheritance.
• If we don't write any constructor for a class, C# provides an implicit default
constructor, i.e., a constructor with no argument.
• Constructors cannot return any value.
• Constructors can be overloaded.
The syntax for a constructor is as follows:
[modifier] name (parameters)
{ // constructor body}
A constructor can have the following modifiers. public, protected, internal, private, extern
Two types: Static or class constructors & Non–static or instance constructors
Static Constructors
• A static constructor or class constructor gets called when the class is instantiated or a
static member of the class is used for the first time.
• A Static constructor cannot be overloaded.
• It should be without parameters and can only access static members.
• It cannot have any access modifiers.
• The static constructor for a class executes only once in an application domain.
• Static constructors cannot be chained with other static or non-static constructors.
• Static Constructor Executes Before an Instance Constructor.
In the program that follows, the static constructor is invoked once the static variable of the class is
referenced.
using System;
class Test
{
private static int i;
static Test()
{
Console.WriteLine ("Static Constructor.");
}
public static int Assign
{
set
{
i = value;
}
get
{
return i;
}
}
}
class Sample
{
public static void Main()
{
Test.Assign = 2;
}
}
Listing 2: Static Constructor Executes Before an Instance Constructor
using System;
class TestClass
{
static TestClass ()
{
System.Console.Write("Static ");
}
public TestClass ()
{
System.Console.Write("Instance ");
}
}
class Test
{
static void Main()
{
new TestClass ();
Console.ReadLine ();
}
}
The output of the above program is 'Static Instance'. A static constructor can only access static
members of a class. The reason is that at the time when a static constructor is loaded in the
memory, the instance members of a class are not available. In the following program, the
assignment to the non–static integer variable p inside the static constructor is an error.
Listing 3: Static Constructor Can Access Only Static Members
class Test
{
int p;
static Test()
{
p = 9;
}
public static void Main(string []args)
{
Test testObject = new Test();
/*Error: An object reference is required for the
non-static field, method,
or property 'Test.p'*/
}
}
Non-Static or Instance Constructors
Non-static constructors are also called instance constructors, type constructors, or type
initializers, and are used to create and initialize instances of the class they belong to. We can
have multiple non-static constructors but only one static constructor for a class. A non-static
constructor with no parameters is called the default constructor. If we do not write any constructor
for a class, the compiler automatically supplies one. This is the implicit default constructor. This
property of C# to supply an implicit default constructor is revoked once we write any constructor
for a class.
Non-static constructors can be public, private, protected, external, or internal. A public constructor
is one that is called when the class is instantiated. A private constructor is one that prevents the
creation of the object of the class. It is commonly used in classes that contain only static
members. A class containing an internal constructor cannot be instantiated outside of the
assembly. An internal constructor can be used to limit concrete implementations of the abstract
class to the assembly defining the class. A protected constructor allows the base class to do its
own initialization when subtypes are created. When constructor declaration includes an extern
modifier, the constructor is said to be an external constructor. An external constructor declaration
provides no actual implementation and hence does not contain any definition. It is to be noted
that a public constructor can access a private constructor of the same class through constructor
chaining.
Listing 4: Public Constructor Can Access Private Constructor of the Same Class
using System;
class Test
{
public Test(): this(10)
{
Console.WriteLine("Default Constructor");
}
private Test(int intValue)
{
Console.WriteLine("Parameterized Constructor");
}
public static void Main(string []args)
{
Test testObject = new Test();
Console.ReadLine ();
}
}
The output is as follows:
Parameterized Constructor
Default Constructor
A protected constructor can only be invoked from the subclasses of the class in which it is
defined. This is illustrated in the example that follows.
Listing 5
using system;
class B
{
protected B (string s) {}
}
class D : B
{
public D () : base ("Called from D class") {}
}
class E
{
public static void Main(string []args)
{
B x = new B ("Called from E class");
/*Error. The constructor test.B.B(string s) is inaccessible due to its
protection level*/
}
}
Constructor Overloading
A constructor can take zero or more arguments as parameters. A constructor with zero arguments
is known as the default constructor. We can have multiple constructors in a class with different
sets of signatures. Such constructors are known as “overloaded constructors”. The overloaded
constructors of a class must differ in their number of arguments, type of arguments, and/or order
of arguments. This gives the user the ability to initialize the object in multiple ways.
The class in the program shown below contains three constructors. The first is the default
constructor, followed by the two argument constructors. Note that the constructors differ in their
signature.
Listing 6: Overloaded Constructors
using system;
public class Test
{
public Test()
{
//Default constructor
}
public Test(int sampleValue)
{
// This is the constructor with one parameter.
}
public Test(int firstValue, int secondValue)
{
// This is the constructor with two parameters.
}
}
Constructor Chaining
Constructor chaining refers to the ability of a class to call one constructor from another
constructor. In order to call one constructor from another, we use base (parameters) or : this
(parameters) just before the actual code for the constructor, depending on whether we want to
call a constructor in the base class or in the current class.
Listing 7: Constructor Chaining
using system;
public class Test
{
public Test(): this(10)
{
// This is the default constructor
}
public Test(int firstValue)
{
// This is the constructor with one parameter.
}
}
public Base(int x)
{
Console.WriteLine("Base Constructor Version 2");
}
}
class MyClient
{
public static void Main()
{
Derived dObject = new Derived();
//Displays 'Base Constructor Version 2' followed by 'Derived Constructor'.
}
}
Constructors are executed in the order of inheritance as shown in the example below.
Listing 9: Order of Execution of Constructors in Inheritance
using System;
class Base
{
public Base()
{
Console.WriteLine("Base constructor");
}
}
class Derived : Base
{
public Derived()
{
Console.WriteLine("Derived constructor");
}
}
class Test
{
public static void Main()
{
Derived dObject = new Derived();
//Displays 'Base constructor' followed by 'Derived constructor'.
}
}
It is not possible to inherit a class that has only a private constructor.
Listing 10: Private Constructors Prevent Inheritance
using system;
class Base
{
Base( )
{
}
}
class Derived : Base // Syntax Error.
{
public static void Main()
{
Derived dObject = new Derived ();
}
}
Conclusion
The best practice is to always explicitly specify the constructor, even if it is a public default
constructor. Proper design of constructors goes a long way in solving the challenges faced in
class designs.
C# Delegates Explained
A delegate is an object that refers to a static method or an instance method
A delegate is an object that is created to refer to a static method or an instance method, and then
used to call this method. To start off, you create a new delegate type in a different way than you
create any other class. You use the delegate keyword as in the following statement.
public delegate int DelegateToMethod(int x, int y);
The First Delegate Example
using System;
namespace Delegates
{
public delegate int DelegateToMethod(int x, int y);
using System;
namespace Delegates
{
public class Math
{
// note that the delegate now is a nested type of the Math class
public delegate void DelegateToMethod(int x, int y);
Operator Overloading In C#
The mechanism of giving a special meaning to a standard C# operator with respect to a user
defined data type such as classes or structures is known as operator overloading. Remember
that it is not possible to overload all operators in C#. The following table shows the operators and
their overloadability in C#.
Operators Overloadability
+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.
==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.
=, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded
In C#, a special function called operator function is used for overloading purpose. These special
function or method must be public and static. They can take only value arguments. The ref and
out parameters are not allowed as arguments to operator functions.
The general form of an operator function is as follows.
public static return_type operator op (argument list)
Where the op is the operator to be overloaded and operator is the required keyword. For
overloading the unary operators, there is only one argument and for overloading a binary operator
there are two arguments. Remember that at least one of the arguments must be a user-defined
type such as class or struct type.
Overloading Unary Operators The general form of operator function for unary operators is as
follows. public static return_type operator op (Type t) { // Statements } Where Type must be a
class or struct. The return type can be any type except void for unary operators like +, ~, ! and dot
(.). but the return type must be the type of 'Type' for ++ and o remember that the true and false
operators can be overloaded only as pairs. The compilation error occurs if a class declares one of
these operators without declaring the other.
The following program overloads the unary - operator inside the class Complex
// Unary operator overloading
using System;
class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{
x = i;
y = j;
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex();
c2.ShowXY(); // displays 0 & 0
c2 = -c1;
c2.ShowXY(); // diapls -10 & -20
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex(20,30);
c2.ShowXY(); // displays 20 & 30
Complex c3 = new Complex();
c3 = c1 + c2;
c3.ShowXY(); // dislplays 30 & 50
}
}
The binary operators such as = =, ! =, <, >, < =, > = can be overloaded only as pairs. Remember
that when a binary arithmetic operator is overloaded, corresponding assignment operators also
get overloaded automatically. For example if we overload + operator, it implicitly overloads the + =
operator also.
Summary
1.The user defined operator declarations can't modify the syntax, precedence or associativity of
an operator. For example, a + operator is always a binary operator having a predefined
precedence and an associativity of left to right.
2.User defined operator implementations are given preference over predefined implementations.
3.Operator overload methods can't return void.
4.The operator overload methods can be overloaded just like any other methods in C#. The
overloaded methods should differ in their type of arguments and/or number of arguments and/or
order of arguments. Remember that in this case also the return type is not considered as part of
the method signature.
// calculate factorial
txtNumber.Text = "";
txtNumber.Focus();
}
Or
private bool CheckPalindrome(string myString)
{
string strrevs="";
foreach char c in myString
{
strrevs= c + strrevs;
}
if (strrevs==myString)
return true;
else
return false;
}
In web.congig you can add key and its value.And that key value u can retrive like
string connectionString = System.Configuration.ConfigurationSettings.AppSettings
["conStringWeb"].ToString()
Here conStringWeb is my key and i access its value.
How to write unmanaged code and how to identify whether the code is managed /
unmanaged ? Answer
you can only write unmanaged code in c# not in vb.net you can only call unmanaged code in
vb.net. calling and writing unmanaged code are different things.
To identify whether the code is managed or not open the file in ildasm in VS.Net Command
prompt.Also you can use a .Net tool called dumpbin, which can be
used to check the headers.
or open the dll in notepad and check for "V e r s i o n".
If you find that, it is managed assembly.
How Web Services help Us? What r the difference between Remoting and webservices
Web services are those services delivered via web and assume that ur project comprising of
timezone of u.s you need not write a code for that just call in the web method
you need for that time
Difference:-The ultimate difference between these two is When u have both client and server @
your end you can use webservices and when u have either the client or the server @ your end it
will be awesome if you opt Remoting
In remoting objects communicates thru homogineous protocols i.e.,TCP.Where as Webservices
provides funtionality thru hetrogenious protocals i.e., HTTP,SOAP.
In remoting data is passed as streams whereas webservices communicates in XML Format
If we add a textbox and give the required field validator,and i add two radio buttons 1 is
yes another one is No.And i add another one server control button ,if i click the button ,if
the radio button Yes is checked the validation control is fired ,if no the validation control is
not fired.So what you used to solve this problem. Answer
We can add the code in page_load
One Listbox showing all cities. If you select one city in list box the information related to
that particular city should be displayed in Datagrid . How do you do that? Answer
protected void ddlcity_SelectedIndexChanged(object sender,
EventArgs e)
{
sqlConnection con= new sqlConnection(" ");
string str="select * from table where city ='" +
ddlcity.SelectItem.Text ="'";
sqlDataAdapter da= new slqDataAdapter(str,con)
dataset ds = new dataset;
da.fill(ds,"City");
dgview.datasource=ds.tables["City"];
dgview.dataBind();
}
}
catch
{ }}}
Dategrid filtering and sorting How can we sort all the fields at once? Answer
Undoubtedly u need to write a sql query for this with the order by (or) sort by.
And also call the subroutine that fills the datagrid after each insert or delete so that u can see the
changes at the runtime with the new alignment(i mean sorting)...