Reputation:
Say I have an old class, dated from c# 1.1 and I would like to add more methods, fields to it. Now I am using 2005, and thus the most logical solution is to use partial classes. However, it seems that I have to pretend word partial to every class in a file where I define it.
The problem:
What if I cannot change the class declaration in an old file (add word partial to it), but still want to add methods to it, what should I do?
Upvotes: 0
Views: 183
Reputation: 95432
Well, firstly, yes you do need to use the partial keyword to all of the involved classes, under the same namespace. This will tell the compiler that those are the parts of the same class that will be put together.
Now, if you really cannot change the old classes, one thing you can do is to inherit your old class:
public class NewClass : OldClass
...and as such you can extend the functionality of the OldClass.
You may also choose to just consume the old class some sort of wrapper, as an attribute/property:
public class NewClass
{
public OldClass MyClass { get; set; } //.NET 3.5 / VS2008
private OldClass _oldClass; //.NET 2.0 / VS2005
public OldClass MyClass
{
get { return _oldClass; }
set { _oldClass = value; }
}
}
...or even a generic:
public class NewClass<T> where T: OldClass //applicable in both versions
The suggestion for extension methods will also work:
public void NewMethod1(this OldClass, string someParameter){} //available only in .NET 3.5/VS2008
Upvotes: 10
Reputation: 754715
If you're using VS2005 and you cannot modify the old class then really there is nothing you can do. If you were using VS2008 you could use extension methods to "simulate" adding new classes but nothing in 2005 will help you.
You're only possible option is really to subclass if possible and add new methods that way. Probably not going to fix the problem you're having though.
Why can you not change the old file? That seems fairly extreme.
Upvotes: 0
Reputation: 59645
You cannot do anything. You are not allowed to edit the old file, so you cannot add members to this file. Also you cannot add the partial
keyword and add the members in another file.
The only ways out might be to write an extension methods (requires C# 3.0) or to create a derived class. Both solution do not (really) modify the original class.
Upvotes: 0
Reputation: 18181
Here is my order:
Upvotes: 0