SachaV

Hi all,

I was just browsing msdn to get to know .net (especially c#) a little bit better, when I came accross a code construction I had never seen:

new private string Id
{
get
{
return id;
}
set
{
id = value;
}
}

I usually declare properties without the "new" keyword. I didn't find any explanation so I'd hoped maybe someone here can help me a bit further

Always interested in learning .net Wink.

Thanks in advance.

Sacha.



Re: Visual C# Language new keyword in property declaration

Jeremy Filburn

Polymorphism:

Replacing a member of a base class with a new derived member requires the new keyword. If a base class defines a method, field, or property, the new keyword is used to create a new definition of that method, field, or property on a derived class. The new keyword is placed before the return type of a class member that is being replaced.

For more info please see this source: Polymorphism Overview






Re: Visual C# Language new keyword in property declaration

SachaV

Oh I see.

Well it seems something worthy of rememberance Smile.

Thank you!





Re: Visual C# Language new keyword in property declaration

Jazz4sale

The IDE will let you know when you need to use it and it will also let you know if you don't.






Re: Visual C# Language new keyword in property declaration

Sam Pearson

If the OP doesn't mind me asking another related question, what is the benefit of using the 'new' keyword, rather than overriding the method (assuming the base class' method is marked virtual or can be modified to be virtual)





Re: Visual C# Language new keyword in property declaration

Jazz4sale

No benefit unless you have a new implemenation. Your new property might have some extra functionality that the base class does not offer.




Re: Visual C# Language new keyword in property declaration

ben.biddington

Actually I'm not sure it is polymorphism, since you get a different implementation of the property depending on the declared type of object.

You'll only get the new property value when you use a reference of the derived type.

It's this side-effect that makes me dislike the new modifier