Monday, March 26, 2012

Why new

Hey i m kindoff new to .net. I couldnt figure out why use the new keyword for declaring the functions in the inherited class. Only thing which i could find out was that if the signature of the function in the base class and the derived class are the same, then there is a warning that u need to use the new keyword and if we put the new keyword the warning goes off. But what actually does that warning means.

jaitleycheck out the following

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfNewOpPG.asp
Does that mean that new is only for putting off that warning as stated on the msdn in the article u refernced.

"If you remove the new modifier, the program will still compile and run, but you will get the warning:"

-jaitley
i'm quite intruiged by this.. i'm a vb.net developer and i was trying to work out the equivalent (if there is one)

i used lutz roeders reflector and reversed engineered the c# to vb.net, in fact the c# had lost the new keyword


public void HelloWorld
{
}

public sub HelloWorld
end Sub

I think the new keyword is an equivalent to the vb.net shadows keyword, which hides all implementations of a particular method in the base class. So if the base class has 3 helloworlds with different argument signatures, the derived class can hide them all using the shadows keyword.
Yes that is true that new keyword is similar to shadows of vb.net
but by query still remains - what does hiding means.
any lights!!

-jaitley
if we have (in a base class)

Called Class1


public function helloWorld() as string
end function

public function HelloWorld(byval x as string) as string
end function

public function HelloWorld(byval y as long) as string
end function

in the derived class...

Called Class2


public shadows function HelloWorld() as string
end function

When we create a Class2 instance we only have one HelloWorld, all 3 in the base class are hidden by the one in the derived class because of the shadows keyword (or new in c#). (the class itself can internally access the base class 3 HelloWorld methods.

You cannot use shadows/new and overrides together.

does this make sense?
Hi !!!

I am a bit confused i still what exactly shadows/new do and why we use them? I hope you explain with giving example how can benefit of shadows/new?

I appreciate your help!!
Hey Richy
i guess that is not what i found out by trying the same thing as u told...i tried

class a
{
public void fun()
{
Console.Read();
}
public void fun(int x)
{
}
public void fun(int x, int y)
{
}
}
class b : a
{
new public void fun(int x)
{
Console.Write("just having fun");
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
b b1 = new b();
b1.fun();
}
}

and it worked fine. So still new remains a mystry.

-jaitley
Any Comments?

-jaitley
new = override

0 comments:

Post a Comment