The public new overridden int ID

As with most days I learn things about programming and C# that I didn't know before, until I've already past the point where I know I'll never ever come close knowing everything.

Now, I though I knew a bit about method/property modifiers, well apparently not, found one today that I haven't seen before.

*Unexpected places to find 'new':
*
Maybe I've been living under a rock for quiet some time, but I'm talking about the keyword 'new'. And I bet the first this that's come to mind is 'what kind of developer are you? everyone knows about 'new'!

Well it just turns out that I've never seen 'new' used like this (and hopefully I've got this right):

public class Address
{
private int _id;
public int ID
{
get{ return _id; }
set{ _id = value; }
}
} //all good so far!

public class PersonalAddress : Address
{
private int _personalAddressId;
public new int ID
{
get{ return _personalAddressId; }
set{ _personalAddressId = value; }
}

So for anyone who is also living under the rock with me, this in fact 'overrides' the ID property only when the instance is (PersonalAddress) and even though Address.ID is not marked as virtual. When it is cast back to (Address) then the ID field from the Address base class is used. So the PersonalAddress class effectively has 2 ID fields but they are only accessible are the respective layers.

Two in a row, and some lessons in generics:
So while I was searching (unsuccessfully) to find an example of this in the docs, I stumbled across my second find of the day. 'New' and Generics! For a while I've been thinking that generics is all well and good changing type 'T' to whatever is defined, but how do you restrict certain types for 'T'. Well it might look a little something like this:

public class DataReaderBlogDataProvider : BlogDataProvider
where T : MySqlDataHandler, new()
{
...
}

So what does this mean? Well it basically says that you can pass any class that fits MySqlDataHandler in as 'T' that has a 'public new()' constructor.

And wait there's more, you can also define multiple constraints for 'T':

class EmployeeList where T : Employee, IEmployee, System.IComparable, new()
{
// ...
}

But wait theres more still, generics goes all the way with 'Naked Type Constraints':

public class SampleClass where T : V { }

And I think that's enough for one night. But, now I've seen this I'm keen to see what other funky uses of everyday keywords I can dig up.

Posted by: Brendan Kowitz
Last revised: 21 Sep 2013 12:13PM

Comments

No comments yet. Be the first!

No new comments are allowed on this post.