Wednesday, April 27, 2005

SubClassing in C#

After years of coding in C# it feels a bit embarassing to be posting this... But

public class person
{
private person(){/* ...Constructor implementation... */ }
// ... More Attributes and Methods...
}

public class customer : person
{
public customer () { /* ...Constructor implementation... */ }
// ... More Attributes and Methods...
}

in the above code snippet .NET fires a compile time error basically becuase 'person' has a private constructor! It's a no brainer than you can't directly create objects out of classes which have private constructor - but sub classing them - well, i couldn't say for sure that that sub classing wasn't allowed too until that code snippet had been punched in and tried out!

public class person
{
public person() {/* ...Constructor implementation... */ }
// ... More Attributes and Methods...
}

public class customer : person
{
public customer () { /* ...Constructor implementation... */ }
// ... More Attributes and Methods...
}

The above code, of course works! Moral of the story - all classes that you want to sub class must have public / protected constructors. All classes that you want to create objects out of must have public / protected constrctors... and even after years of coding there's always something we're either yet to learn or have conveniently forgotten!

1 Comments:

Anonymous Anonymous said...

subclassing is somewhat different to deriving a subclass.

11:42 AM  

Post a Comment

<< Home