Hi....
I want to know use of 'new' and 'this ' keyword in C# ? Please explain with an example in details ?
Thanks.....
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Mukesh KumarPosted Jan 9, 2012, 11:26 PM
new keyword can be used as an operator or as a modifier.
new operator : Used to create objects on the heap and invoke constructors.
MyClass ObjMyClass = new MyClass();
new modifier : Used to hide an inherited member from a base class member.
public class MyBaseC
{
public int x;
public void Invoke() { }
}
Declaring a member with the name Invoke in a derived class will hide the method Invoke in the base class, that is:
public class MyDerivedC : MyBaseC
{
new public void Invoke() { }
}
The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.
public Customer(string FirstName, string LastName)
{
this.firstname = FirstName;
this.lastname = LastName;
}
AartiPosted Jan 10, 2012, 12:09 AM
this Keyword
C# supports this keyword which provides access to the current class instance. One of uses of this keyword is to resolve scope ambiguity, which can arise when an incoming parameter is named identically to a data field of the type as shown in the following example:
class ToyCar
{
public string name;
public int speed;
public void SetName(string name)
{
name = name;
}
...
}
The code will compile just fine, however, as shown in the following example, the value of the name filed is an empty string.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleClasses
{
class ToyCar
{
public string name;
public int speed;
public ToyCar() { }
public void SetName(string name)
{
name = name;
}
public ToyCar(int s)
{
speed = s;
}
public void PrintState()
{
Console.WriteLine("{0}'s speed is {1} mph.", name, speed);
}
static void Main(string[] args)
{
ToyCar myToy = new ToyCar(100);
myToy.SetName("Boong Boong");
myToy.PrintState();
Console.WriteLine();
}
}
}
Output shows the name field is empty.
's speed is 100 mph.
The problem is that the implementation of SetName() is assigning the incoming parameter back to itself given that the compiler assumes name is referring to the variable currently in the method scope rather than the name field at the class scope. To inform the compiler that we want to set the current object's name field to the incoming name parameter, simply use this to resolve the ambiguity:
public void SetName(string name)
{
this.name = name;
}
If there is no ambiguity, we are not required to use this keyword when a class wants to access its own data or members. For example, if we rename the string data member to nameToy, the use of this is optional as there is no longer a scope ambiguity:
class ToyCar
{
public string nameToy;
public int speed;
public ToyCar() { }
public void SetName(string name)
{
nameToy = name;
this.nameToy = name;
}
...
}
Constructor Chaining with this keyword
Another way of using this keyword is to design a class using constructor chaining. This is helpful when we have a class that defines multiple constructors. Given the fact that constructors often validate the incoming arguments to enforce various rules, it can be common to find redundant validation logic within a class's constructor set.
class ToyCar
{
public string nameToy;
public int speed;
public ToyCar() { }
public void SetName(string name)
{
this.nameToy = name;
}
public ToyCar(int s)
{
if(s < 10)
speed = 10;
speed = s;
}
public ToyCar(string n, int s)
{
if (s < 10)
speed = 10;
speed = s;
nameToy = n;
}
...
}
In the example code above, each constructor is ensuring that the speed level is never less than 10. While this is all well, we have redundant code in tow constructors and we are required to update code in multiple locations if our rules change.
One way to improve the situation is to define a method in the ToyCar class that will validate the incoming argument(s). If we were to do so, each constructor could make a call to this method before making the field assignment(s). While this approach does allow us to isolate the code we need to update when rules change, we are not dealing with the following redundancy:
class ToyCar
{
public string nameToy;
public int speed;
public ToyCar() { }
public void SetName(string name)
{
this.nameToy = name;
}
public ToyCar(int s)
{
SetSpeed(s);
}
public ToyCar(string n, int s)
{
SetSpeed(s);;
nameToy = n;
}
public void SetSpeed(int s)
{
if (s < 10)
speed = 10;
speed = s;
}
...
}
Another approach is to designate the constructor that takes the greatest number of argumentsas the master constructor and have its implementation perform the required validation logic. The remaining constructors can use this keyword to forward the incoming arguments to the master constructor and provide any additional parameters as necessary. In this way, we only need to worry about maintaining a single constructor for the entire class while the remaining constructors are empty.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleClasses
{
class ToyCar
{
public string nameToy;
public int speed;
public ToyCar() { }
public ToyCar(int s) : this("", s) {}
public ToyCar(string n) : this(n, 0) { }
public ToyCar(string n, int s)
{
if (s < 10)
speed = 10;
speed = s;
nameToy = n;
}
public void SetName(string name)
{
this.nameToy = name;
}
public void PrintState()
{
Console.WriteLine("{0}'s speed is {1} mph.", nameToy, speed);
}
static void Main(string[] args)
{
ToyCar myToy = new ToyCar(100);
myToy.SetName("Boom Boom Boom");
myToy.PrintState();
Console.WriteLine();
}
}
}
Output is:
Boom Boom Boom's speed is 100 mph.
When chaining constructors, note how this keyword is dangling off the constructor's declaration with a colon outside the scope of the constructor itself.
New Keyword
In C#, the new keyword can be used as an operator or as a modifier.
Example: Class1 MyClass = new Class1();
It is also used to invoke the default constructor for value types, for example:
int myInt = new int();
The new operator cannot be overloaded.
If the new operator fails to allocate memory, it throws the exception OutOfMemoryException.
Example
In the following example, a struct object and a class object are created and initialized by using the new operator and then assigned values. The default and the assigned values are displayed
// cs_operator_new.cs
// The new operator
using System;
class NewTest
{
struct MyStruct
{
public int x;
public int y;
public MyStruct (int x, int y)
{
this.x = x;
this.y = y;
}
}
class MyClass
{
public string name;
public int id;
public MyClass ()
{
}
public MyClass (int id, string name)
{
this.id = id;
this.name = name;
}
}
public static void Main()
{
// Create objects using default constructors:
MyStruct Location1 = new MyStruct();
MyClass Employee1 = new MyClass();
// Display values:
Console.WriteLine("Default values:");
Console.WriteLine(" Struct members: {0}, {1}",
Location1.x, Location1.y);
Console.WriteLine(" Class members: {0}, {1}",
Employee1.name, Employee1.id);
// Create objects using parameterized constructors::
MyStruct Location2 = new MyStruct(10, 20);
MyClass Employee2 = new MyClass(1234, "John Martin Smith");
// Display values:
Console.WriteLine("Assigned values:");
Console.WriteLine(" Struct members: {0}, {1}",
Location2.x, Location2.y);
Console.WriteLine(" Class members: {0}, {1}",
Employee2.name, Employee2.id);
}
}
Output
Default values:
Struct members: 0, 0
Class members: , 0
Assigned values:
Struct members: 10, 20
Class members: John Martin Smith, 1234
Notice in the example that the default value of a string is null. Therefore, it was not displayed.
Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.
Consider the following class:
public class MyBaseC
{
public int x;
public void Invoke() {}
}
Declaring a member with the name Invoke in a derived class will hide the method Invoke in the base class, that is:
public class MyDerivedC : MyBaseC
{
new public void Invoke() {}
}
However, the field x will not be affected because it is not hidden by a similar name.
Name hiding through inheritance takes one of the following forms:
It is an error to use both new and override on the same member.
Using the new modifier in a declaration that does not hide an inherited member generates a warning.
Example
In this example, a base class, MyBaseC, and a derived class, MyDerivedC, use the same field name x, thus hiding the value of the inherited field. The example demonstrates the use of the new modifier. It also demonstrates how to access the hidden members of the base class by using the fully qualified names.
// cs_modifier_new.cs
// The new modifier
using System;
public class MyBaseC
{
public static int x = 55;
public static int y = 22;
}
public class MyDerivedC : MyBaseC
{
new public static int x = 100; // Name hiding
public static void Main()
{
// Display the overlapping value of x:
Console.WriteLine(x);
// Access the hidden value of x:
Console.WriteLine(MyBaseC.x);
// Display the unhidden member y:
Console.WriteLine(y);
}
}
Output
Copy
100
55
22
If you remove the new modifier, the program will still compile and run, but you will get the warning:
The keyword new is required on 'MyDerivedC.x' because it hides inherited member 'MyBaseC.x'.
You can also use the new modifier to modify a nested type if the nested type is hiding another type, as demonstrated in the following example.
Example
In this example, a nested class, MyClass, hides a class with the same name in the base class. The example demonstrates using the new modifier to eliminate the warning message, as well as accessing the hidden class members by using the fully qualified names.
// cs_modifer_new_nested.cs
// Using the new modifier with nested types
using System;
public class MyBaseC
{
public class MyClass
{
public int x = 200;
public int y;
}
}
public class MyDerivedC : MyBaseC
{
new public class MyClass // nested type hiding the base type members
{
public int x = 100;
public int y;
public int z;
}
public static void Main()
{
// Creating object from the overlapping class:
MyClass S1 = new MyClass();
// Creating object from the hidden class:
MyBaseC.MyClass S2 = new MyBaseC.MyClass();
Console.WriteLine(S1.x);
Console.WriteLine(S2.x);
}
}
Output
100
200
Satyapriya NayakPosted Jan 9, 2012, 11:15 PM
In C#, the new keyword can be used as an operator or as a modifier.
The new operator is used to create objects and invoke constructors,
for example:
Class1 MyClass = new Class1();
The this keyword refers to the current instance of the class.
public Employee(string name, string alias)
{
this.name = name;
this.alias = alias;
}
Thanks