John Wesley Harding

Tried with this a couple of times now on different projects, the first time I came to the conlcusion that if I did not understand it then no point in trying to write that kind of code and just continued with what I knew...

This time its bugging me, it seems to be what I need but I dont know how to expose its benefits...

For instanct, in my project I wish to gather information from a native .NET class but also I have other properties that I feel belong in there and so wish to extend the class. I just cant figure it out though so at the moment I have 3 classes, ie. MyClass1, MyClass2, MyExtendedProperties - where MyClass's expose the properties of an instantiated object plus share MyExtendedProperties methods to expose my own.

so why wont this work ...

class MyString : String[]

{

public MyString()

{

}

}

class Program

{

void Main(...)

{

MyString s = new string[0];

}

}

When I do that kind of thing I find two problems, the most serious is the fact it wont compile!...Cannot explicitly convert type ...The second is just my mind pondering so I need to get the fact that it wont compile out of the way first - Or am I doing this completely wrong

Thanks alot for any help.

JWH



Re: Visual C# Language Using Inheritance\Derivation

OmegaMan

You want to mix a type and an array and derive from it which cannot be done. One can extend the string class by inheriting from string such as

public class stringEx : string

and that is that. If you need multiple items of this specialized class then do this

List<stringEx> myStrings = new List<StringEx>();

which will then give you the power of arrays.






Re: Visual C# Language Using Inheritance\Derivation

Thomas Danecker

You should not use inheritance here. You should always prefer compositon over inheritance. That means you should do the following instead. If you want to access the array like you do it normally, you could add an indexer.

Code Snippet

class MyString

{

string[] myArray;

int anotherField;

float thirdFiled;

public string this[int index]

{

get { return myArray[index]; }

set { myArray[index] = value; }

}

public MyString()

{

}

}