Blog author:
Sabarimahesh | Posted on: 5/19/2012 | Category:
C# Blogs | Views: 728 | Status:
[Member] |
Points: 75
|
Alert Moderator
Introduction
Through this topic I'm going to share about new KeyWord in C#
I believe that this will be very much helpful for beginners
- new Operator is used to create objects and Call on constructors
And also create instances for anonymous types
Example 1
To Create an Object
ClassA Cat= new ClassA ();
ClassA Rat=new ClassA();
Here,Cat and Rat are Objects of ClassA
Example 2
To Create instance for anonymous types
var Cat = new { Dotnet= "Rat" }
Console.WriteLine(Cat.Dotnet );
Here,Cat is an object for anonymous
Example 3
To Call on Default Constructor
string str = new string ();
Here,str is an object.Once it is created, default constructor is called
- Hides a member inherited from a base class.
- i.e., Derived-Class me replaces the Base-Class.
- We can hide without the use of the new modifier, a warning will be generated.
- If we need to avoid the warning, the new modifier is a must.
- The New Modifier will hide in class or struct the following items from all base class members with the same name
1) Constant
2) Field
3) Property
4) Method
5) Indexer
Example 1
Class BaseClass consists of function Show().
Class DerivedClass hides the function Show()
class Program
{
static void Main(string[] args)
{
Baseclass bc;
bc = new Baseclass();
bc.Show();
Console.ReadLine();
}
}
class Baseclass
{
public void Show()
{
System.Console.WriteLine("Baseclass::Show");
}
}
class DerivedClass : Baseclass
{
new public void Show()
{
System.Console.WriteLine("DerivedClass::Show");
}
}
Output
Baseclass::Show
Show() of class BaseClass is executed because the reference variable b refers to the object of class BaseClass.
- Any type argument in a generic class declaration should have a public parameter less constructor.
- Apply the new constraint to a type parameter when the generic class creates new instances of the same type.
Example 1
class ItemFactory<T> where T
: new()
{
public T GetNewItem()
{
return new T();
}
}
Example 2
public class ItemFactory<T> where T : IComparable, new()
{
}
Conclusion
We have learned about new Keyword. I hope that my article was helpful.
Life is a Race
Thanks & Regards
By
Sabari Mahesh P M
Found interesting? Add this to: