Reducing duplication of code within two classes that have differing nested classes - c#

I have two classes (this is C#) that are very similar except they each contain their own nested class and enum.
I would like to refactor them to both inherit from a single abstract class, but I'm running into a problem because the methods are all tightly coupled to the nested class types.
My first plan was to pull out the ItemDetails Class, but it is linked to the ItemType, which is an enum that is specific to each view item class. Further, I can't just use System.Enum as the type since I need to be able to serialize the details to an xml file.
How could I reduce the duplication within these classes?
public class FirstViewItem
{
[Serializable]
public class ItemDetails
{
public ItemType Type;
public int Width;
public string Text;
public int DisplayOrder;
}
public enum ItemType
{
None = 0,
A,
B,
C
}
public FirstViewItem()
{
// ...
}
public List<ItemDetails>()
{
// code here ...
}
}
public class SecondViewItem
{
[Serializable]
public class ItemDetails
{
public ItemType Type;
public int Width;
public string Text;
public int DisplayOrder;
}
public enum ItemType
{
None = 0,
X,
Y,
X
}
public SecondViewItem()
{
// ...
}
public List<ItemDetails>()
{
// code here ...
}
}

You want to make a generic class that is dependent on the item type enum being passed in:
public class ViewItem<T>
{
[Serializable]
public class ItemDetails
{
public T Type; // the generic type is inserted here
public int Width;
public string Text;
public int DisplayOrder;
}
// common code that uses ItemDetails
}
Then some item types:
public enum FirstItemType
{
None = 0,
A,
B,
C
}
public enum SecondItemType
{
None = 0,
X,
Y,
Z
}
Then usage:
var firstViewItem = new ViewItem<FirstItemType>();

Yamen's answer is good.
I'd started writing this so i'll finish. Here's an example of using generics with a base class and some inheriting classes:
public class BaseClass<T>
{
public T NestedClass{get;set;}
}
public class MainOne : BaseClass<MainOneType>
{
}
public class MainTwo : BaseClass<MainTwoType>
{
}
public class MainOneType
{
}
public class MainTwoType
{
}

I ended up using ideas from 2 different answers, so I'll answer with the combined result.
public class BaseViewItem<T> where T : struct
{
[Serializable]
public class ItemDetails
{
public T Type;
public int Width;
public string Text;
public int DisplayOrder;
}
public FirstViewItem()
{
// ...
}
public List<ItemDetails>()
{
// code here ...
}
}
public class FirstViewItem : BaseViewItem<FirstItemType>
{
// class-specific code...
}
public class SecondViewItem : BaseViewItem<SecondItemType>
{
// class-specific code...
}
public enum FirstItemType
{
None = 0, A, B, C
}
public enum SecondItemType
{
None = 0, X, Y, Z
}

Related

How to set all properties of base class through derived class

public BaseClass
{
prop abc;
prop pqr;
prop xyz;
}
public DerivedClass : BaseClass
{
prop New1;
prop New2;
//constructor
public DerivedClass(BaseClass baseObj,someMore params)
{
this.abc = baseObj.abc;
this.pqr = baseObj.pqr;
this.xyz = baseObj.xyz;
/* I do not want to do this for each and every property as I have more than 40 properties */
}
}
Here in above code How I can set all properties of derived class which are same in derived class as base class.
In my derived class
Can I do somethign of following type to achieve above thing without using Automapper or Reflection
public DerivedClass(BaseClass baseObj,someMore params):base(baseObj) //or something similar
{
}
You could initialize the properties in your base class instead of the derived class (since both the parameter and the base classes share the same type of class).
To copy the properties, besides AutoMapper (which I find really slow) and reflection (which is hard to implement and maintain), an easy, very efficient way to do this is using the open source library Omu.ValueInjecter:
Install the library from NuGet:
Install-Package ValueInjecter -Version 3.1.3
Then, use it in your constructor as follows:
using Omu.ValueInjecter;
public abstract class BaseClass
{
protected BaseClass(BaseClass baseObj)
{
this.InjectFrom(baseObj);
}
public string Abc { get; set; }
public int Pqr { get; set; }
public object Xyz { get; set; }
}
public class DerivedClass : BaseClass
{
public DerivedClass(BaseClass baseObj, int new1, object new2) : base(baseObj)
{
New1 = new1;
New2 = new2;
}
public int New1 { get; set; }
public object New2 { get; set; }
}
The first time you run this code, it will create a mapper and store it in memory so the following times you perform the same operation will be much faster.
If you don't want to use value injecter or any other library, simply set the properties manually in your base class.
public abstract class BaseClass
{
protected BaseClass(BaseClass baseObj)
{
Abc = baseObj.Abc;
Pqr = baseObj.Pqr;
Xyz = baseObj.Xyz;
}
[...]
}
You can use prototype pattern. If you use C#, Please refer code as below:
public abstract class BaseClass
{
public int a;
public int b;
public int c;
public abstract BaseClass Clone();
}
public class DerivedClass : BaseClass
{
public int new1;
public int new2;
public override BaseClass Clone()
{
return this.MemberwiseClone() as BaseClass;
}
public override string ToString()
{
return string.Format("{0}{1}{2}{3}{4}", a, b, c, new1, new2);
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass AClass = new DerivedClass();
AClass.a = 1;
AClass.b = 2;
AClass.c = 3;
DerivedClass BClass = AClass.Clone() as DerivedClass;
BClass.new1 = 4;
BClass.new2 = 5;
Console.WriteLine(BClass.ToString());
}
}
It comes from https://mobilechos.blogspot.com/2019/04/prototype-pattern-with-csharp.html.

Access const with generics C#

I have the following base class:
public class Base
{
public string LogicalName { get; set; }
public int NumberOfChars { get; set; }
public Base()
{
}
public Base(string logicalName, int numberOfChars)
{
LogicalName = logicalName;
NumberOfChars = numberOfChars;
}
}
and the following derived classes:
public class Derived1 : Base
{
public const string EntityLogicalName = "Name1";
public const int EntityNumberOfChars = 30;
public Derived1() : base(EntityLogicalName, EntityNumberOfChars)
{
}
}
public class Derived2 : Base
{
public const string EntityLogicalName = "Name2";
public const int EntityNumberOfChars = 50;
public Derived2()
: base(EntityLogicalName, EntityNumberOfChars)
{
}
}
and I also have this function that is provided by a service:
public IEnumerable<T> GetEntities<T>(string entityName, int numberOfChars) where T : Base
{
//Some code to get the entities
}
My problem is how can I call this function generically? I want to call it with something that looks like this:
public void TestEntities<T>() where T : Base
{
var entities = GetEntities<T>(T.EntityLogicalName, T.EntityNumberOfChars);
//some other code to test the entities
}
This of course doesn't work because at this point T is not known. How can I accomplish something similar to this? EntityLogicalName and EntityNumberOfChars are characteristics that all Base derived classes have and they never change for each derived class. Can I get them from the Base class without instantiating objects or some other way that I am not seeing?
Replace constants with getter abstract properties
public abstract class Base
{
public abstract string LogicalName { get; }
public abstract int NumberOfChars { get; }
public Base()
{
}
}
public class Derived1 : Base
{
public string LogicalName { get { return "Name1"; } }
public int NumberOfChars { get { return 30; } }
public Derived1() : base()
{
}
}
Also, you will be able to put some logic into overriden getter, e.g. :
...
public string LogicalName { get { return this.EntityMap.Name; } }
...
UPDATE: The fact that you do not want to instantiate object from class but want to be able to get that string in a strongly typed manner can be handled in one more way. It is totally separate from answer above ( Since you can't override static props in c#). Consider the following code. We are adding one more class here, but LocatorInner can be a member of BaseClass. We are using this approach a lot in several existing apps.:
public class Locator
{
public static class LocatorInner<T> where T : BaseClass
{
public static string Name { get; set; }
}
public static string GetName<T>() where T : BaseClass
{
return LocatorInner<T>.Name;
}
public static void SetName<T>(string name) where T : BaseClass
{
LocatorInner<T>.Name = name;
}
}
public class BaseClass
{
}
public class DerivedClass: BaseClass
{
static DerivedClass()
{
Locator.LocatorInner<DerivedClass>.Name = "me";
}
}
public class TestClass<T> where T : BaseClass
{
public void Method()
{
var name = Locator.GetName<T>();
}
}
IMHO, I believe using constants here is a bad design decision.
You can either solve the issue using #vittore approach, but for me it sounds like you should use meta-programming with attributes if you're looking to get data from the T generic argument
For example, what about:
public class LogicalNameAttribute : Attribute
{
public LogicalNameAttribute(string name)
{
Name = name;
}
public string Name { get; private set; }
}
public class NumberOfCharsAttribute : Attribute
{
public NumberOfCharsAttribute (int number)
{
Number = number;
}
public string Number { get; private set; }
}
[LogicalName("Name1"), NumberOfChars(30)]
public class Derived1 : Base
{
public Derived1() : base()
{
}
}
Now your service method can extract attribute metadata as follows:
public void TestEntities<T>() where T : Base
{
LogicalNameAttribute logicalNameAttr = typeof(T).GetCustomAttribute<LogicalNameAttribute>();
NumberOfCharsAttribute numberOfCharsAttr = typeof(T).GetCustomAttribute<NumberOfCharsAttribute >();
Contract.Assert(logicalNameAttr != null);
Contract.Assert(numberOfCharsAttr != null);
string logicalName = logicalNameAttr.Name;
int numberOfChars = numberOfCharsAttr.Number;
// Other stuff
}
There's a performance penalty because you need to use reflection to get attributes applied to T, but you gain the flexibility of not forcing derived classes to provide this static info.
As #vittore mentioned, move the properties to base,pass the hard coded values from derived and in creation use just defautl(T)
public IEnumerable<T> GetEntities<T>(string entityName, int numberOfChars) where T : Base
{
yield return default(T); //Is its always class use new constraint and return new T();
}

How to compare and sort subclasses?

For example I have these class and subclasses.
class Program
{
static void Main(string[] args)
{
var animals = new List<Animal> { new Wolf {kills = 5},
new Rabbit {name = "Uncle John"},
new Eagle {eyeCount = 1},
new Wolf {kills = 100},
new Rabbit { name = "Human" } };
animals.Sort();
//Suposted to be: Rabbit(Human), Rabbit(Uncle John), Wolf(5), Wolf(100), Eagle(1)
}
}
enum SortOrder { Rabbit, Wolf, Eagle }
abstract class Animal{}
class Wolf : Animal
{
public int kills = 0; //Marked public for simple initialization
}
class Rabbit : Animal
{
public string name = "Funny Little Guy"; //Marked public for simple initialization
}
class Eagle : Animal
{
public byte eyeCount = 2; //Marked public for simple initialization
}
I want to sort list of animals. 1)Sort among the other objects of same type (sort Wolves by kill, rabbits by name, etc) 2) Sort groups of subclasses in "SortOrder", so Rabbits goes first in the list and Eagles last.
I had tried make this by implementing IComparable<Animal>, IComparable<Wolf>, IComparable<Rabbit>, IComparable<Eagle> interfaces, but this lead me to nowhere, because I couldn't make this work and even though I could, adding 1 more subclass cause a lot code work.
This is my trying:
abstract class Animal : IComparable<Animal>, IComparable<Wolf>, IComparable<Rabbit>, IComparable<Eagle>
{
public abstract int CompareTo(Animal other);
public abstract int CompareTo(Wolf other);
public abstract int CompareTo(Rabbit other);
public abstract int CompareTo(Eagle other);
}
class Wolf : Animal
{
public int kills = 0; //Marked public for simple initialization
public override int CompareTo(Animal other) => other.CompareTo(this);
public override int CompareTo(Wolf other) => kills.CompareTo(kills);
public override int CompareTo(Rabbit other) => SortOrder.Wolf.CompareTo(SortOrder.Rabbit);
public override int CompareTo(Eagle other) => SortOrder.Wolf.CompareTo(SortOrder.Eagle);
}
But by doing this way I getting reverse order, and As I said its hard to add new subclasses.
So what is efficient way to make this kind of comparison?
To minimize adding new code and force new class to add to the hierarchy I would do this kind of design:
First, I would implement IComparable for each concrete animal type. This is simple. Second, I would add SortOrder OrderType property to the abstract class and implement it in each concrete instance. This would force whoever extends the class to re-evaluate the enum and probably add new value to it. Then, the main compare function would first check this property. If not equal, then return the comparison between types. If equal, just call compare on the two instances, because it can be safely assumed they are of same type.
Implemented it here. I actually had to use reflection, because there is no other way to call concrete comparer. But it seems to work pretty nicely, as long as the actual type corresponds to returned enum.
enum SortOrder { Rabbit, Wolf, Eagle }
abstract class Animal : IComparable<Animal>
{
public abstract SortOrder OrderType { get; }
public int CompareGeneric(Animal x, Animal y)
{
// use reflection to call comparer on concrete animal type
var comparerType = typeof(IComparable<>).MakeGenericType(x.GetType());
var compareMethod = comparerType.GetMethod("CompareTo");
return (int)compareMethod.Invoke(x, new object[] { y });
}
public int Compare(Animal x, Animal y)
{
// clever hack to compare the enums
var diff = x.OrderType - y.OrderType;
if (diff != 0)
return diff;
return CompareGeneric(x, y);
}
public int CompareTo(Animal other)
{
return Compare(this, other);
}
}
class Wolf : Animal, IComparable<Wolf>
{
public override SortOrder OrderType { get { return SortOrder.Wolf; } }
public int kills = 0; //Marked public for simple initialization
public int CompareTo(Wolf other)
{
return this.kills.CompareTo(other.kills);
}
}
class Rabbit : Animal, IComparable<Rabbit>
{
public override SortOrder OrderType { get { return SortOrder.Rabbit; } }
public string name = "Funny Little Guy"; //Marked public for simple initialization
public int CompareTo(Rabbit other)
{
return this.name.CompareTo(other.name);
}
}
class Eagle : Animal, IComparable<Eagle>
{
public override SortOrder OrderType { get { return SortOrder.Eagle; } }
public byte eyeCount = 2; //Marked public for simple initialization
public int CompareTo(Eagle other)
{
return this.eyeCount.CompareTo(other.eyeCount);
}
}
I think you can implement IComparable with Animal class and use a read only SortOrder enum property as Euphoric mentioned.
Then in each class you can override CompareTo method to compare each species with their kind.
public abstract class Animal : IComparable
{
public abstract SortOrder SortOrder { get; }
public virtual int CompareTo(object obj)
{
Animal rightValue = (Animal)obj;
return this.SortOrder < rightValue.SortOrder ? -1
: this.SortOrder > rightValue.SortOrder ? 1 : 0;
}
}
public class Wolf : Animal
{
public override SortOrder SortOrder { get { return SortOrder.Wolf; } }
public int kills = 0; //Marked public for simple initialization
public override int CompareTo(object obj)
{
if (obj is Wolf)
{
Wolf rightValue = (Wolf)obj;
return this.kills < rightValue.kills ? -1
: this.kills > rightValue.kills ? 1 : 0;
}
else
{
return base.CompareTo(obj);
}
}
}
public class Rabbit : Animal
{
public override SortOrder SortOrder { get { return SortOrder.Rabbit; } }
public string name = "Funny Little Guy"; //Marked public for simple initialization
public override int CompareTo(object obj)
{
if (obj is Rabbit)
{
Rabbit rightValue = (Rabbit)obj;
return String.Compare(this.name, rightValue.name);
}
else
{
return base.CompareTo(obj);
}
}
}
public class Eagle : Animal
{
public override SortOrder SortOrder { get { return SortOrder.Eagle; } }
public byte eyeCount = 2; //Marked public for simple initialization
public override int CompareTo(object obj)
{
if (obj is Eagle)
{
Eagle rightValue = (Eagle)obj;
return this.eyeCount < rightValue.eyeCount ? -1
: this.eyeCount > rightValue.eyeCount ? 1 : 0;
}
else
{
return base.CompareTo(obj);
}
}
}
I would add an SortKey and the ICompareable Interface to your Animal class and implement the logic in derived class.
abstract class Animal : IComparable<Animal>
{
public abstract int SortKey { get; }
public abstract int CompareTo(Animal other);
}
class Wolf : Animal
{
public int kills = 0; //Marked public for simple initialization
public override int SortKey { get { return 100; } }
public override int CompareTo(Animal other)
{
if (other.SortKey != SortKey)
{
return SortKey.CompareTo(other.SortKey);
}
var otherWolf = other as Wolf;
if (otherWolf == null)
{
return -1;
}
return kills.compareTo(otherWolf.kills);
}
}
Consider using an IComparer across types; and implement IComparable for ordering within the specific type. The Comparer would call the Comparable only for same-type comparisons.
Advantage(s):
None of the types needs to know it's "relative" sorting key between types. In addition the base type is not 'dirtied' with an additional field. (Although there is nothing preventing putting the ordering in such a 'SortKey'-field.)
The rules for ordering types of animals is isolated in one location, the Comparer.
The rule for ordering within an animal type is already
handled by the IComparable and can be overridden/specialized
for each type.
Disadvantage(s):
The collection / ordering operation needs to use the Comparer
Comparer adds "hidden" logic that may need to be updated for additional types. (This is only required if not using a 'SortKey'-like approach in a base type.)
Using a separate IComparaer/IComparable approach is a more generic form of using a 'SortKey' field, with the additional ordering mixed into the IComparable, because such a field could be used by such a IComparer implementation.
I would solve your Problem with Linq
using System.Collections.Generic;
using System.Linq;
public enum SortOrder
{
Rabbit,
Wolf,
Eagle
}
public class Program
{
public static void Main(string[] args)
{
var animals = (new List<Animal> { new Wolf {Kills = 5},
new Rabbit {Name = "Uncle John"},
new Eagle {EyeCount = 1},
new Wolf {Kills = 100},
new Rabbit { Name = "Human" } })
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.Classifier);
//Suposted to be: Rabbit(Human), Rabbit(Uncle John), Wolf(5), Wolf(100), Eagle(1)
}
}
public abstract class Animal
{
public abstract object Classifier { get; }
public string Name { get; set; }
public SortOrder SortOrder { get; set; }
}
public class Eagle : Animal
{
public Eagle()
{
this.SortOrder = SortOrder.Eagle;
}
public override object Classifier
{
get { return this.EyeCount; }
}
public byte EyeCount { get; set; }
}
public class Rabbit : Animal
{
public Rabbit()
{
this.Name = "Funny Little Guy";
this.SortOrder = SortOrder.Rabbit;
}
public override object Classifier
{
get { return this.Name; }
}
}
public class Wolf : Animal
{
public Wolf()
{
this.Name = "Funny Little Guy";
this.SortOrder = SortOrder.Wolf;
}
public override object Classifier
{
get { return this.Kills; }
}
public int Kills { get; set; }
}

C#: Confusion about Interfaces, Implementation and Inheritance

I'm wondering about what's the way to go, if I need to publicate data-interfaces but want to use them internal with extended calculated properties. To make it clearer:
// The public interface
public interface IData
{
int Property { get; }
}
// The internal interface
internal interface IExtendedData : IData
{
int ExtendedProperty { get; }
}
// The assumed implementation of someone using my interface
public class Data : IData
{
public Data(int a)
{
Property = a;
}
public int Property
{
get;
private set;
}
public override string ToString()
{
return Property.ToString();
}
}
// My implementation
internal class ExtendedData : IExtendedData
{
public ExtendedData(int a)
{
Property = a;
}
public int Property
{
get;
private set;
}
public int ExtendedProperty
{
get
{
return 2 * Property;
}
}
public override string ToString()
{
return Property.ToString() + ExtendedProperty.ToString();
}
}
// publicated by me, for the person who uses my dll
public static class Calculations
{
public static int DoSomeCalculation(IData data, int parameter)
{
// This probably don't work, but maybe shows what I want to do
IExtendedData tempData = (ExtendedData)data;
return tempData.ExtendedProperty * parameter;
}
}
I'm realy frustrated, cause I feel like missing some basical programing skills.
You could solve this problem by implementing ExtendedData as a Wrapper for a class implementing IData
internal class ExtendedData : IExtendedData
{
private IData data;
public ExtendedData(IData data)
{
this.data = data;
}
public int Property
{
get { return data.Property; }
private set { data.Property = value; }
}
public int ExtendedProperty
{
get
{
return 2 * Property;
}
}
}
and use this in DoSomeCalculation like
IExtendedData tempData = new ExtendedData(data);
ExtendedData could inherit from Data:
class ExtendedData : Data
{...}
And for creation of a Data object you add a factory like so:
public class DataFactory
{
public IData CreateData()
{
return new ExtendedData();
}
}
User have to create all its Data objects by this factory. You can ensure it by making Data's constructor internal.
In your DLL you can then cast to ExtendedData.

Override abstract readonly property to read/write property

I would like to only force the implementation of a C# getter on a given property from a base abstract class. Derived classes might, if they want, also provide a setter for that property for public use of the statically bound type.
Given the following abstract class:
public abstract class Base
{
public abstract int Property { get; }
}
If I want a derived class that also implements a setter, I could naively try:
public class Derived : Base
{
public override int Property
{
get { return field; }
set { field = value; } // Error : Nothing to override.
}
private int field;
}
But then I get a syntax error since I try to override the non existing setter. I tried some other way such as declaring the base setter private and such and I still stumble upon all kind of errors preventing me from doing that. There must be a way to do that as it doesn't break any base class contract.
Incidentaly, it can be done with interfaces, but I really need that default implementation.
I stumbled into that situation so often, I was wondering if there was a hidden C# syntax trick to do that, else I will just live with it and implement a manual SetProperty() method.
You can't do it directly, since you can't new and override with the same signature on the same type; there are two options - if you control the base class, add a second property:
public abstract class Base
{
public int Property { get { return PropertyImpl; } }
protected abstract int PropertyImpl {get;}
}
public class Derived : Base
{
public new int Property {get;set;}
protected override int PropertyImpl
{
get { return Property; }
}
}
Else you can introduce an extra level in the class hierarchy:
public abstract class Base
{
public abstract int Property { get; }
}
public abstract class SecondBase : Base
{
public sealed override int Property
{
get { return PropertyImpl; }
}
protected abstract int PropertyImpl { get; }
}
public class Derived : SecondBase
{
public new int Property { get; set; }
protected override int PropertyImpl
{
get { return Property; }
}
}
Would this suit your needs?
public abstract class TheBase
{
public int Value
{
get;
protected set;
}
}
public class TheDerived : TheBase
{
public new int Value
{
get { return base.Value; }
set { base.Value = value; }
}
}
The virtual was removed, but the base value is still the only storage for the value. So this should show '5'. And the compiler should fuss about b.Value = 4;
TheDerived d = new TheDerived();
d.Value = 5;
TheBase b = d;
//b.Value = 4; // uncomment for compiler error
cout << "b.Value == " << b.Value << endl;
-Jesse
What about something like:
public abstract class Base
{
public virtual int Property
{
get { return this.GetProperty(); }
set { }
}
protected abstract int GetProperty();
}
I had a similar requirement where I needed an interface to be able to share common sorting functionality between two loosely related classes. One of them had a read-only Order property and the other had a read-write Order property, but I needed a way to read the property the same way from both classes.
It turns out that this can be done by hiding the read-only value in a derived interface. Here is how I did it.
interface ISortable
{
int Order { get; }
}
interface ISortableClass2
: ISortable
{
// This hides the read-only member of ISortable but still satisfies the contract
new int Order { get; set; }
}
class SortableClass1
: ISortable
{
private readonly int order;
public SortableClass1(int order)
{
this.order = order;
}
#region ISortable Members
public int Order
{
get { return this.order; }
}
#endregion
}
class SortableClass2
: ISortableClass2
{
#region ISortableClass2 Members
public int Order { get; set; }
#endregion
}
class RunSorting
{
public static void Run()
{
// Test SortableClass1
var list1 = new List<SortableClass1>();
list1.Add(new SortableClass1(6));
list1.Add(new SortableClass1(1));
list1.Add(new SortableClass1(5));
list1.Add(new SortableClass1(2));
list1.Add(new SortableClass1(4));
list1.Add(new SortableClass1(3));
var sorted1 = SortObjects(list1);
foreach (var item in sorted1)
{
Console.WriteLine("SortableClass1 order " + item.Order);
}
// Test SortableClass2
var list2 = new List<SortableClass2>();
list2.Add(new SortableClass2() { Order = 6 });
list2.Add(new SortableClass2() { Order = 2 });
list2.Add(new SortableClass2() { Order = 5 });
list2.Add(new SortableClass2() { Order = 1 });
list2.Add(new SortableClass2() { Order = 4 });
list2.Add(new SortableClass2() { Order = 3 });
var sorted2 = SortObjects(list2);
foreach (var item in sorted2)
{
Console.WriteLine("SortableClass2 order " + item.Order);
}
}
private static IEnumerable<T> SortObjects<T>(IList<T> objectsToSort) where T : ISortable
{
if (objectsToSort.Any(x => x.Order != 0))
{
return objectsToSort.OrderBy(x => x.Order);
}
return objectsToSort;
}
}
You may do this with a constructor as following;
public abstract class Base
{
public abstract int Property { get; }
}
public class Derived : Base
{
public Derived(string Property) : base(Property)
{
}
}

Categories