Optional Parameters in Abstract method? Is it possible? - c#

I have a abstract base class.
I have 2 derived classes from this base class.
Is there anyway that one of my classes can ignore the string parameter in the abstract overide usage?
Or do I have to just send in a blank one and ignore it? (making readability drop slightly)
Can I have one function that has some sort of optional parameter so that both of the following derived classes would compile?
PS - The following code is riddled with in-compilable code for the example of what I would like to do
PS PS - Yes i have compiled the following code already - see above comment for outcome
public abstract class MyBaseClass
{ //optional string?
public abstract void FunctionCall(int i, string s = "");
}
public class MyDerivedClass : MyBaseClass
{
public override void FunctionCall(int i)
{
MessageBox.Show(i.ToString());
}
}
public class YourDerivedClass : MyBaseClass
{
public override void FunctionCall(int i, string s)
{
MessageBox.Show(s + " " + i.ToString());
}
}

If you don't absolutely need FunctionCall to be abstract, you can declare two versions of it:
public abstract class MyBaseClass
{
public virtual void FunctionCall(int i)
{
this.FunctionCall(i, "");
}
public virtual void FunctionCall(int i, string s)
{
}
}
public class MyDerivedClass : MyBaseClass
{
public override void FunctionCall(int i)
{
MessageBox.Show(i.ToString());
}
}
public class YourDerivedClass : MyBaseClass
{
public override void FunctionCall(int i, string s)
{
MessageBox.Show(s + " " + i.ToString());
}
}
Otherwise, if it must be abstract to ensure it is implemented, you could still add two versions, it just makes the inheritors more verbose:
public abstract class MyBaseClass
{
public abstract void FunctionCall(int i);
public abstract void FunctionCall(int i, string s);
}
public class MyDerivedClass : MyBaseClass
{
public override void FunctionCall(int i, string s)
{
throw new NotImplementedException();
}
public override void FunctionCall(int i)
{
MessageBox.Show(i.ToString());
}
}
public class YourDerivedClass : MyBaseClass
{
public override void FunctionCall(int i)
{
throw new NotImplementedException();
}
public override void FunctionCall(int i, string s)
{
MessageBox.Show(s + " " + i.ToString());
}
}

It will throw a compile error: "Abstract Inherited member 'MyBaseClass.FunctionCall(int, string)' is not implemented".
So no, the short answer is you can't do this.
Instead, you would have to do method overloading and implement BOTH abstract methods.
public abstract class MyBaseClass
{
public abstract void FunctionCall(int i);
public abstract void FunctionCall(int i, string s = "");
}
public class MyDerivedClass : MyBaseClass
{
public override void FunctionCall(int i, string s = "") { }
public override void FunctionCall(int i)
{
MessageBox.Show(i.ToString());
}
}
public class YourDerivedClass : MyBaseClass
{
public override void FunctionCall(int i, string s)
{
MessageBox.Show(s + " " + i.ToString());
}
public override void FunctionCall(int i) {}
}
However this seems quite messy. Perhaps the best option is to always use the optional parameter and simply not pass in a value if it is not needed or handle it as you already seem to be doing.
public class MyDerivedClass : MyBaseClass
{
public override void FunctionCall(int i, string s = "")
{
if (!string.IsNullOrEmpty(s))
MessageBox.Show(i.ToString());
else
// handle other path here
}
}

One possible way is to use extension methods to add missing overrides (which also works with interfaces)
static class MyBaseClassExtensions
{
public void FunctionCall(MyBaseClass this item, int i)
{
item.FunctionCall(i, null);
}
}

Related

"CS0109: The member 'member' does not hide an inherited member. The new keyword is not required" - is this actually true?

I've read other threads and Eric Lippert's posts on the subject, but haven't seen this exact situation addressed anywhere.
C# optional parameters on overridden methods
Optional parameters and inheritance
I'm trying to implement the following situation:
public class BaseClass
{//ignore rest of class for now
public void DoThings(String str)
{
//dostuff
}
}
public class DerivedClass: BaseClass
{//ignore rest of class for now
new public void DoThings(String str, Int32 someint = 1)
{
//dostuff but including someint, calls base:DoThings in here
}
}
When I do this the compiler gives me the warning in the subject line that I do not need to use the new keyword because the method does not hide the inherited method. However I do not see a way to call the base method from the object instance, so it looks hidden to me.
I want it to actually be hidden. If it is not hidden, there is potential for some other user to some day call the base method directly and break the class (it involves thread safety).
My question is, does the new method actually hide the inherited method (compiler is wrong?) or is the compiler correct and I need to do something else to hide the original method? Or is it just not possible to achieve the desired outcome?
void DoThings(String str) accepts a single parameter
void DoThings(String str, Int32 someint = 1) accepts two parameters
=> the methods are distinct, unrelated methods, which incidentally share the name.
Default parameters are inserted at the call-sites during compilation.
Here is one possible solution:
public class BaseClass
{
public virtual void DoThings(String str)
{
//dostuff
}
}
public class DerivedClass: BaseClass
{
public override void DoThings(String str)
{
DoThings(str, 1); // delegate with default param
}
public void DoThings(String str, Int32 someint)
{
//dostuff
}
}
Note that new makes it possible to call base classes' virtual methods in the first place by having a reference with static type of the base class (e.g. by casting it to the base class):
public class Test
{
public static void Main()
{
var obj = new DerivedClass();
BaseClass baseObj = obj;
obj.DoThings("a");
baseObj.DoThings("b");
((BaseClass)obj).DoThings("c");
}
}
class BaseClass
{
public void DoThings(String str)
{
Console.WriteLine("base: " + str);
}
}
class DerivedClass: BaseClass
{
new public void DoThings(String str, Int32 someint = 1)
{
Console.WriteLine("derived: " + str);
base.DoThings(str);
}
}
Output:
derived: a
base: a
base: b
base: c
If you want callers to never call the overridden method of a base class, mark it virtual and override it (like already shown at the top of this answer):
public class Test
{
public static void Main()
{
var obj = new DerivedClass();
BaseClass baseObj = obj;
obj.DoThings("a");
baseObj.DoThings("b");
((BaseClass)obj).DoThings("c");
}
}
class BaseClass
{
public virtual void DoThings(String str)
{
Console.WriteLine("base: " + str);
}
}
class DerivedClass: BaseClass
{
// "hide" (override) your base method:
public override void DoThings(String str)
{
// delegate to method with default param:
this.DoThings(str);
}
public void DoThings(String str, Int32 someint = 1)
{
Console.WriteLine("derived: " + str);
base.DoThings(str);
}
}
Output:
derived: a
base: a
derived: b
base: b
derived: c
base: c
After discussion in the comments: you do not want to use inheratince here, but rather opt for compisition.
The code could look like the following:
public class Test
{
public static void Main()
{
var obj = new DerivedClass(new BaseClass());
obj.DoThings("a");
// baseObj.DoThings("b"); // not accessible
// ((BaseClass)obj).DoThings("c"); // InvalidCastException!
}
}
class BaseClass
{
public void DoThings(String str)
{
Console.WriteLine("base: " + str);
}
}
class Wrapper
{
private BaseClass original;
public Wrapper(BaseClass original) {
this.original = original;
}
public void DoThings(String str, Int32 someint = 1)
{
Console.WriteLine("wrapped: " + str);
original.DoThings(str);
}
}
Output:
base: a
wrapped: a
the 'new' keyword can't be used where you used it
To hide the member:
public class BaseClass
{ // ignore rest of class for now
public virtual void DoThings(String str)
{
// dostuff
}
}
public class DerivedClass: BaseClass
{ //ignore rest of class for now
public override void DoThings(String str)
{
// dostuff
}
public void DoThings(String str, Int32 someint = 1)
{
// do stuff but including some int, calls base:DoThings in here
}
}

Using base class and base interface in C#

I am reshaping an entire system that does not use base classes and base interfaces.
My idea to do so is to extract all the common methods to a base classes and base interfaces.
So basically, we would have:
A base class SomeClassBase implementing an interface ISomeClassBase
A derived class SomeClassDerived implementing ISomeClassDerived (this interface deriving from ISomeClassBase)
Now the problem, how can I instantiate "_mySession" in the derived class (which has a different cast than in the base class), while preserving all the methods from the base class:
public class SomeClassBase : ISomeClassBase
{
public IMySessionBase _mySession = MySession.Instance();
public SomeClassBase ()
{
_mySession.connect(); // Needed??
}
public void doSomething()
{
_mySession.doSomething();
}
}
public class SomeClassDerived : SomeClassBase, ISomeClassDerived
{
public IMySessionDerived _mySession = MySession.Instance();
public SomeClassDerived ()
{
_mySession.connect();
}
public void doSomethingElse()
{
_mySession.doSomethingElse();
}
}
One more thing, IMySessionDerived implements IMySessionBase.
Do not redefine _mySession Let it come from base class.
However in you Derived class you can still reassign.
public class SomeClassDerived : SomeClassBase, ISomeClassDerived
{
public SomeClassDerived ()
{
_mySession = MySession.Instance(); //Declaration comes from base class automatically
_mySession.connect();
}
public void doSomethingElse()
{
_mySession.doSomethingElse();
}
}
If your IMySessionBase and IMySessionDerived are following Hierarchy, it should work. But in some rare cases, You might end up getting into a DoubleDispatchProblem.
As Pointed out in commens, If you want to do something from IMySessionDerived you can add a Property.
public class SomeClassDerived : SomeClassBase, ISomeClassDerived
{
IMySessionDerived _derivedSessionAccessor=> _mySession as IMySessionDerived;
}
Update: To fix the exact design problem here,
Instead of deriving from the base class, have it as a field. And inherit from interface. So Instead of doing above approach,
do like,
public class SomeClassBase : ISomeClassBase
{
public IMySessionBase _mySession ;
public SomeClassBase ( IMySessionBase session)
{
_mySession=session;
_mySession.connect(); // Needed??
}
public void doSomething()
{
_mySession.doSomething();
}
}
public class SomeClassDerived : , ISomeClassDerived
{
public IMySessionDerived _mySession = MySession.Instance();
private SomeClassBase _baseClassInstance;
public SomeClassDerived ()
{
_baseClassInstance=new SomeClassBase(_mySession);
//_mySession.connect();
}
public void doSomethingElse()
{
_baseClassInstance.doSomethingElse();
}
}
Pasting #Selvin answer instead of the link buried in the comments:
The trick here is to use the keyword "base()"
using System;
using System.Runtime.CompilerServices;
public class Program
{
public static void Main()
{
var o1 = new O1();
o1.DS1();
var o2 = new O2();
o2.DS1();
o2.DS2();
}
public class Session1
{
protected readonly Type ownerType;
public Session1(Type type)
{
ownerType = type;
}
public virtual void DS1([CallerMemberName] string functionName = "")
{
Console.WriteLine(ownerType.Name + ":" + GetType().Name + ":" + functionName);
}
}
public class Session2 : Session1
{
public Session2(Type type):base(type) { }
public virtual void DS2([CallerMemberName] string functionName = "")
{
Console.WriteLine(ownerType.Name + ":" + GetType().Name + ":" + functionName);
}
}
public class O1
{
private readonly Session1 t;
public O1() : this(new Session1(typeof(O1))) { }
protected O1(Session1 t)
{
this.t = t;
}
public void DS1()
{
t.DS1();
}
}
public class O2 : O1
{
private readonly Session2 t;
public O2() : this(new Session2(typeof(O2))) { }
protected O2(Session2 t) : base(t)
{
this.t = t;
}
public void DS2()
{
t.DS2();
}
}
}

Intelligent Generic Static Method

I wrote C# code as described below that inherits a class from a generic class with static methods. I want to call the child class for its static methods (inherited from the base class) without having to specify the type.
EDITED! More "real" code
public class Rec
{
public string Name { get; set; }
public override string ToString() { return this.Name; }
public virtual void Load() { /* HERE IT READS A TEXT FILE AND LOAD THE NAME */ }
}
public class BaseClass<T> : Rec
{
public T Argument { get; set; }
public override void Load() { /* NOW IT LOADS ALSO THE ARGUMENT */ }
public static H Method<H>() where H : Rec, new()
{
H iH = new H();
iH.Load();
iH.Name += " " + iH.Argument.ToString();
return iH;
}
}
public class Child : BaseClass<string> { }
public class SomeOtherClass
{
public void Test()
{
Child i = Child.Method();
//instead of Child.Method<Child>();
}
}
So, instead of having to call method<h>() i'd like to just call method(), so the code should assume that "h" is the caller type. Like in:
How can I do it?
Static methods are not inherited in C#
See this answer for an idea of a potential implementation: Stack Overflow whats-the-correct-alternative-to-static-method-inheritance
You could change method<h> to method and make it an instance method:
public class BaseClass<T> where T, new()
{
public T method() { /* RETURN SOMETHING */ }
}
And then call it as follows:
public class ABC : Child
{
public void Test()
{
var iABC = this.method();
}
}

Clone derived class from base class method

I have an abstract base class Base which has some common properties, and many derived ones which implement different logic but rarely have additional fields.
public abstract Base
{
protected int field1;
protected int field2;
....
protected Base() { ... }
}
Sometimes I need to clone the derived class. So my guess was, just make a virtual Clone method in my base class and only override it in derived classes that have additional fields, but of course my Base class wouldn't be abstract anymore (which isn't a problem since it only has a protected constructor).
public Base
{
protected int field1;
protected int field2;
....
protected Base() { ... }
public virtual Base Clone() { return new Base(); }
}
public A : Base { }
public B : Base { }
The thing is, since I can't know the type of the derived class in my Base one, wouldn't this lead to have a Base class instance even if I call it on the derived ones ? (a.Clone();) (actually after a test this is what is happening but perhaps my test wasn't well designed that's why I have a doubt about it)
Is there a good way (pattern) to implement a base Clone method that would work as I expect it or do I have to write the same code in every derived class (I'd really like to avoid that...)
Thanks for your help
You can add a copy constructor to your base class:
public abstract Base
{
protected int field1;
protected int field2;
protected Base() { ... }
protected Base(Base copyThis) : this()
{
this.field1 = copyThis.field1;
this.field2 = copyThis.field2;
}
public abstract Base Clone();
}
public Child1 : Base
{
protected int field3;
public Child1 () : base() { ... }
protected Child1 (Child1 copyThis) : base(copyThis)
{
this.field3 = copyThis.field3;
}
public override Base Clone() { return new Child1(this); }
}
public Child2 : Base
{
public Child2 () : base() { ... }
protected Child (Child copyThis) : base(copyThis)
{ }
public override Base Clone() { return new Child2(this); }
}
public Child3 : Base
{
protected int field4;
public Child3 () : base() { ... }
protected Child3 (Child3 copyThis) : base(copyThis)
{
this.field4 = copyThis.field4;
}
public override Base Clone()
{
var result = new Child1(this);
result.field1 = result.field2 - result.field1;
}
}
Just override the Clone and have another method to CreateInstance then do your stuff.
This way you could have only Base class avoiding generics.
public Base
{
protected int field1;
protected int field2;
....
protected Base() { ... }
public virtual Base Clone()
{
var bc = CreateInstanceForClone();
bc.field1 = 1;
bc.field2 = 2;
return bc;
}
protected virtual Base CreateInstanceForClone()
{
return new Base();
}
}
public A : Base
{
protected int fieldInA;
public override Base Clone()
{
var a = (A)base.Clone();
a.fieldInA =5;
return a;
}
protected override Base CreateInstanceForClone()
{
return new A();
}
}
I did something similar as Alexander Simonov, but perhaps simpler. The idea is (as I said in a comment) to have just one Clone() in the base class and leave all the work to a virtual CloneImpl() which each class defines as needed, relying on the CloneImpl()s of the base classes.
Creation of the proper type is left to C#'s MemberwiseClone() which will do whatever it takes for the object that's calling. This also obviates the need for a default constructor in any of the classes (none is ever called).
using System;
namespace CloneImplDemo
{
// dummy data class
class DeepDataT : ICloneable
{
public int i;
public object Clone() { return MemberwiseClone(); }
}
class Base: ICloneable
{
protected virtual Base CloneImpl()
{
// Neat: Creates the type of whatever object is calling.
// Also obviates the need for default constructors
// (Neither Derived1T nor Derived2T have one.)
return (Base)MemberwiseClone();
}
public object Clone()
{
// Calls whatever CloneImpl the
// actual calling type implements.
return CloneImpl();
}
}
// Note: No Clone() re-implementation
class Derived1T : Base
{
public Derived1T(int i) { der1Data.i = i; }
public DeepDataT der1Data = new DeepDataT();
protected override Base CloneImpl()
{
Derived1T cloned = (Derived1T)base.CloneImpl();
cloned.der1Data = (DeepDataT)der1Data.Clone();
return cloned;
}
}
// Note: No Clone() re-implementation.
class Derived2T : Derived1T
{
public Derived2T(int i1, int i2) : base(i1)
{
der2Data.i = i2;
}
public string txt = string.Empty; // copied by MemberwiseClone()
public DeepDataT der2Data = new DeepDataT();
protected override Base CloneImpl()
{
Derived2T cloned = (Derived2T)base.CloneImpl();
// base members have been taken care of in the base impl.
// we only add our own stuff.
cloned.der2Data = (DeepDataT)der2Data.Clone();
return cloned;
}
}
class Program
{
static void Main(string[] args)
{
var obj1 = new Derived2T(1,2);
obj1.txt = "this is obj1";
var obj2 = (Derived2T)obj1.Clone();
obj2.der1Data.i++;
obj2.der2Data.i++; // changes value.
obj2.txt = "this is a deep copy"; // replaces reference.
// the values for i should differ because
// we performed a deep copy of the DeepDataT members.
Console.WriteLine("obj1 txt, i1, i2: " + obj1.txt + ", " + obj1.der1Data.i + ", " + obj1.der2Data.i);
Console.WriteLine("obj2 txt, i1, i2: " + obj2.txt + ", " + obj2.der1Data.i + ", " + obj2.der2Data.i);
}
}
}
Output:
obj1 txt, i1, i2: this is obj1, 1, 2
obj2 txt, i1, i2: this is a deep copy, 2, 3
You could do something like this:
public class Base<T> where T: Base<T>, new()
{
public virtual T Clone()
{
T copy = new T();
copy.Id = this.Id;
return copy;
}
public string Id { get; set; }
}
public class A : Base<A>
{
public override A Clone()
{
A copy = base.Clone();
copy.Name = this.Name;
return copy;
}
public string Name { get; set; }
}
private void Test()
{
A a = new A();
A aCopy = a.Clone();
}
But i doubt that it will bring something useful. I'll create another example..
I got another idea using the Activator class:
public class Base
{
public virtual object Clone()
{
Base copy = (Base)Activator.CreateInstance(this.GetType());
copy.Id = this.Id;
return copy;
}
public string Id { get; set; }
}
public class A : Base
{
public override object Clone()
{
A copy = (A)base.Clone();
copy.Name = this.Name;
return copy;
}
public string Name { get; set; }
}
A a = new A();
A aCopy = (A)a.Clone();
But i would go for the Alexander Simonov answer.
If performance is not important for your case, you can simplify your code by creating just one general clone method which can clone whatever to whatever if properties are same:
Base base = new Base(){...};
Derived derived = XmlClone.CloneToDerived<Base, Derived>(base);
public static class XmlClone
{
public static D CloneToDerived<T, D>(T pattern)
where T : class
{
using (var ms = new MemoryStream())
{
using (XmlWriter writer = XmlWriter.Create(ms))
{
Type typePattern = typeof(T);
Type typeTarget = typeof(D);
XmlSerializer xmlSerializerIn = new XmlSerializer(typePattern);
xmlSerializerIn.Serialize(writer, pattern);
ms.Position = 0;
XmlSerializer xmlSerializerOut = new XmlSerializer(typeTarget, new XmlRootAttribute(typePattern.Name));
D copy = (D)xmlSerializerOut.Deserialize(ms);
return copy;
}
}
}
}
Found this question while trying to solve this exact problem, had some fun with LINQPad while at it.
Proof of concept:
void Main()
{
Person p = new Person() { Name = "Person Name", Dates = new List<System.DateTime>() { DateTime.Now } };
new Manager()
{
Subordinates = 5
}.Apply(p).Dump();
}
public static class Ext
{
public static TResult Apply<TResult, TSource>(this TResult result, TSource source) where TResult: TSource
{
var props = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var p in props)
{
p.SetValue(result, p.GetValue(source));
}
return result;
}
}
class Person
{
public string Name { get; set; }
public List<DateTime> Dates { get; set; }
}
class Manager : Person
{
public int Subordinates { get; set; }
}

error when returning generic interface

The following code is a simple example of a program I am writing.
public class Y
{ }
public class X : Y
{ }
public class W : Y
{ }
public interface IAaa<T>
where T : Y
{
void Execute(T ppp);
}
public abstract class Aaa<T> : IAaa<T>
where T : Y
{
public abstract void Execute(T ppp);
}
public class Bbb : Aaa<X>
{
public override void Execute(X ppp)
{ }
}
public class Ccc : Aaa<W>
{
public override void Execute(W ppp)
{ }
}
public class Factory
{
public static IAaa<Y> Get(bool b)
{
if(b)
return new Bbb();
else
return new Ccc();
}
}
class Program
{
static void Main(string[] args)
{
IAaa<Y> aa;
aa = Factory.Get(true);
}
}
when I compile it I get the following errors
error CS0266: Cannot implicitly convert type 'ConsoleApplication3.Bbb'
to 'ConsoleApplication3.IAaa'. An explicit
conversion exists (are you missing a cast?)
error CS0266: Cannot implicitly convert type 'ConsoleApplication3.Ccc'
to 'ConsoleApplication3.IAaa'. An explicit
conversion exists (are you missing a cast?)
Is there any way to make it work?
You can't use the interface in the way you're trying to. Lookup covariance/contravariance, you're trying to do the opposite of what's possible (you have in interface that could be <in T> but you're trying to use it like <out T>).
Take class Bbb for instance - it has an Execute(X) method. What would happen if you tried to pass a Y (which may or may not be an X) to that? The compiler doesn't allow it, because you never defined in the code what should happen in that case.
You can do what you want by creating and implementing another interface, IAaa. E.g.
public interface IAaa
{
void Execute(Y ppp);
}
Perhaps implemented like this, so that if you try to call it with an invalid type, a cast exception is thrown:
void Main()
{
IAaa aa;
aa = Factory.Get(true);
}
public class Y
{ }
public class X : Y
{ }
public class W : Y
{ }
public interface IAaa<T> : IAaa
where T : Y
{
void Execute(T ppp);
}
public interface IAaa
{
void Execute(Y ppp);
}
public abstract class Aaa<T> : IAaa<T>
where T : Y
{
public abstract void Execute(T ppp);
void IAaa.Execute(Y ppp)
{
this.Execute(ppp);
}
protected abstract void Execute(Y ppp);
}
public class Bbb : Aaa<X>
{
public override void Execute(X ppp)
{ }
protected override void Execute(Y ppp)
{
this.Execute((X)ppp);
}
}
public class Ccc : Aaa<W>
{
public override void Execute(W ppp)
{ }
protected override void Execute(Y ppp)
{
this.Execute((W)ppp);
}
}
public class Factory
{
public static IAaa Get(bool b)
{
if(b)
return new Bbb();
else
return new Ccc();
}
}
As the error says, you are missing a cast. I believe this is what you need:
public static IAaa<Y> Get(bool b)
{
if(b)
return (IAaa<Y>)(new Bbb());
else
return (IAaa<Y>)(new Ccc());
}
You could cast to (IAaa<Y>) and your code would compile.
However it will not work and will fail at run-time.
Why?
Your classes Bbb and Ccc are specialized classes and the Execute method cannot process ALL types of Aaa. You have to tell C# / the compiler.
UPDATE:
By having a generic Factory you can get specialized instances of IAaa and your code should work.
In your Program you already know the type as you pass TRUE or FALSE to the Factory, so you need to explicitly tell C# the type of the Interface implementation you want to use.
(refactor the Factory class accordingly, I'm just sending what should compile)
public class Y
{ }
public class X : Y
{ }
public class W : Y
{ }
public interface IAaa<T>
where T : Y
{
void Execute(T ppp);
}
public abstract class Aaa<T> : IAaa<T>
where T : Y
{
public abstract void Execute(T ppp);
}
public class Bbb : Aaa<X>
{
public override void Execute(X ppp)
{ }
}
public class Ccc : Aaa<W>
{
public override void Execute(W ppp)
{ }
}
public class Factory<T> where T : Y
{
public static IAaa<T> Get(bool b)
{
if(b)
return (IAaa<T>)new Bbb();
else
return (IAaa<T>)new Ccc();
}
}
class Program
{
static void Main(string[] args)
{
IAaa<X> aa;
aa = Factory<X>.Get(true);
}
}
UPDATE 2
Just an example of how you could refactor the Factory class:
public class Factory<T, U>
where T : Y
where U : Aaa<T>, new()
{
public static IAaa<T> Get()
{
return (IAaa<T>)new U();
}
}
class Program
{
static void Main(string[] args)
{
IAaa<X> aa;
aa = Factory<X, Bbb>.Get();
}
}

Categories