Self-referential generic class templates - c#

Is it possible to build the following heterogeneous (generic) linked list data type?
class MyClass<TPrev, TNext>
where TNext : MyClass<TPrev2, TNext2>
where TPrev2 : MyClass<TPrev, TNext>
edit: Notice in particular the new type TNext2 which is not defined.
edit2: ... which makes the above snippet non-functional as written.

No, you can't model what you want. You could do this:
class Link<TPrev, TValue, TNext>
{
public TPrev Prev { get; set; }
public TValue Value { get; set; }
public TNext Next { get; set; }
}
But you can't do:
class Link<???, TValue, ???>
{
public Link<???> Prev { get; set; }
public TValue Value { get; set; }
public Link<???> Next { get; set; }
}
The problem is that if you declare that the previous and next elements of your list must also be lists of some generic type, then you've attempted to define a type of infinite size. There's no way to say, "There is no next node after this" because the next node must be a Link<T> for some other link type and you run into an infinite regress.

No, this is not possible because you haven't defined TNext2 or TPrev2 as part of the class definition. You can't have a generic parameter like that unless its an existing type, or is a generic type parameter in the class definition.
But then, if TPrev2 is an existing type, you can't specify a constraint on it like you are trying to do.

Take a look at this blog entry for an interesting idea on the topic. In essence you could do something like this:
public abstract class LinkedListBase<T>
where T : LinkedListBase<T>
{
public T Next { get; set; }
public T Previous { get; set; }
}
public class LinkedListImpl : LinkedListBase<LinkedListImpl>
{
public string Name { get; set; }
// all of the value properties go here...
}
So essentially the value itself contains the links to the previous and next.

Related

Detect nested type of generic

I'm working on a project which needs to determine the type of an object, take the information from that type and move it to a structure that fits in our database.
For this, I'm using Pattern Matching with a case statement which works fine.
The only thing that I got stuck with is that some types have nested types as well. The information in those nested types is the information that I need.
Take a look at the code below:
public class CallAnswered
{
public string Caller { get; set; }
public MetaDataInformation MetaData{ get; set; }
}
public class CallAbandoned
{
public string ReasonForAbandonment{ get; set; }
public MetaDataInformation MetaData { get; set; }
}
public class MetaDataInformation
{
public DateTime ReceivedAt { get; set; }
public DateTime AnsweredAt { get; set; }
}
public void DetermineType<T>(T callEvent)
{
switch (callEvent)
{
case CallAnswered callAnswered:
case CallAbandoned callAbandoned:
// Somehow, I need to access the "MetaData" property as a type
break;
}
}
Like shown in the code above, I am able to detect the parent type and assign it a variable. Bu I have no clue on how to get the nested MetaDataInformation type.
Does anyone have an idea how this can be resolved?
You do not need a generic type here. By deriving from an abstract base class, you can solve two problems.
You can use the base type instead of the generic type and access all the public members of this base class.
You can add an abstract method in the base class implemented in the two derived classes making the switch statement obsolete.
public abstract class Call
{
public MetaDataInformation MetaData { get; set; }
public abstract void Process();
}
public class CallAnswered : Call
{
public string Caller { get; set; }
public override void Process()
{
// TODO: Do Answer things. You can access MetaData here.
}
}
public class CallAbandoned : Call
{
public string ReasonForAbandonment{ get; set; }
public override void Process()
{
// TODO: Do Abandonment things. You can access MetaData here.
}
}
somewhere else
public void ProcessCalls(Call callEvent)
{
// Replaces switch statement and does the right thing for both types of calls:
callEvent.Process();
}
This is called a polymorphic behavior.
See also:
Polymorphism (Wikikpedia)
Polymorphism (Microsoft Docs)

C# Using base or this in inherited get

I am having trouble understanding the proper use of base and this within an inherited get method. I have an interface IMatchModel:
public interface IMatchModel
{
int TypeId { get; }
DateTime DataDate { get; set; }
string TypeName { get; set; }
}
And a base model class TradeModel:
public class TradeModel
{
public long TradeId { get; set; }
public DateTime DataDate { get; set; }
public string TradeName { get; set; }
}
Then I have a class that inherits from TradeModel and implements IMatchModel. I am currently using the following method:
public class TradeMatchModel : TradeModel, IMatchModel
{
public int TypeId { get { return 1; } }
public string TypeName
{
get
{
return base.TradeName;
}
set
{
base.TradeName = value;
}
}
}
The TradeModel class is used within a function that operates on all of its attributes. IMatchModel is used in a function that only needs the attributes contained in the interface. The code works properly, but I still feel like I don't quite understand if it is best to be using base over this. Is the use of base in this context incorrect?
The only time you need to use base is when you are inside a overridden virtual method and you need to call the base implementation of the method you are currently overriding. All other times you can use this..
Also this. is generally not needed unless you have a name conflict between a field or property in the class and a name of a variable or a parameter. 99% of the time you can just leave off the this. and do return TradeName;

C# Interface containing an array of interface, hierarchy

I have an Interface for a master-detail common interface hierarchy:
public interface ITModel
{
ITPeriodHead[] PeriodHeads { get; set; }
}
I try to use it this way:
public class T19Model:ITModel
{
public T19Item[] Items { get; set; }
**public T19PeriodHead[] PeriodHeads { get; set; }**
}
The array of PeriodHeads causes error at compile time,
despite T19PeriodHead implements ITPeriodHead, like this:
public class T19PeriodHead : BaseTPeriodHead, ITPeriodHead
{ ...
What is the solution? If I use the array of ITPeriodHead, I will not be able to access the periodhead items members, properties, methods....
Any help is appriciated.
You have to honor the interface contract. You are returning a more specific class that the interface defines, so you are not fully defining the interface.
You could explicitly implement the interface, but you have an issue with the setter - what if someone tries to set the property to an array of objects that are not T19PeriodHeads?:
public class T19Model:ITModel
{
public T19Item[] Items { get; set; }
public T19PeriodHead[] PeriodHeads { get; set; }
ITPeriodHead[] ITModel.PeriodHeads
{
get {return PeriodHeads;}
set {/* what to do here if value is not an array of T19PeriodHeads? */}
}
}
If you do not need a setter for the array property (maybe an Add method instead?) then you are fine.

automapper: skipping/ignoring nested types

I'm trying to create a map between a domain object and viewmodel to support a use case that feels quite common. The fact that I can't find a solution makes me think I'm approaching the problem incorrectly. Here's some psuedo code that represents my source and destination types:
public class DomainClass
{
public NestedDomainClass1 NestedDomainClass1{ get; set; }
}
public class NestedDomainClass1
{
public NestedDomainClass2 NestedDomainClass2 { get; set; }
}
public class NestedDomainClass2
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
}
public class DomainViewModel
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
}
As you can see, DomainViewModel maps perfectly to DomainClass.NestedDomainClass1.NestedDomainClass2. However, for reasons that aren't entirely relevant, I can't simply create a mapping at that level. Instead I have to map two levels higher:
Mapper.CreateMap<DomainObj, DomainViewModel>();
This is unfortunate, as the minute I do this, I can no longer rely on AutoMapper conventions to automagically map similarly named properties, and I end having to write a lot of highly repetitive code:
Mapper.CreateMap<DomainClass, DomainViewModel>().ForMember(dest=>dest.PropertyA, opt=>opt.MapFrom(source=>source.NestedDomainClass1.NestedDomainClass2.PropertyA));
Mapper.CreateMap<DomainClass, DomainViewModel>().ForMember(dest=>dest.PropertyB, opt=>opt.MapFrom(source=>source.NestedDomainClass1.NestedDomainClass2.PropertyB));
I've played with the RecognizeDestinationPrefixes and RecognizeDestinationPostfixes methods in the hopes of getting AutoMapper to "skip" directly to the property I'd like to map from (NestedDomainClass2), but no luck. Any help would be appreciated!
That's because you're trying map between two completely different types. You really need to do something like this:
Mapper.CreateMap<NestedDomainClass2, DomainViewModel>();
Mapper.AssertConfigurationIsValid();
var dvm = Mapper.Map<NestedDomainClass2, DomainViewModel>
(obj.NestedDomainClass1.NestedDomainClass2);
However if you want to, you can hide that detail by defining a TypeConverter. Something like this should work:
public class DomainTypeConverter : TypeConverter<DomainClass, DomainViewModel>
{
protected override DomainViewModel ConvertCore(DomainClass source)
{
return Mapper.Map<NestedDomainClass2, DomainViewModel>
(source.NestedDomainClass1.NestedDomainClass2);
}
}
You can then define your mapping to be something like this:
Mapper.CreateMap<NestedDomainClass2, DomainViewModel>();
Mapper.CreateMap<DomainClass, DomainViewModel>()
.ConvertUsing(new DomainTypeConverter());
Mapper.AssertConfigurationIsValid();
And use it like this:
var dvm = Mapper.Map<DomainClass, DomainViewModel>(dc);

Help refactor my C# code to be more maintainable and to use best coding practices

I have this C# class structure that I would like to refactor to use best coding standards (use interfaces/abstract classes) so it can be more maintainable and reusable. The code as it is right now isn't awful, but it's not ideal.
I have a series of TableItemGroup classes: AccountTableItemGroup, PendingVoteTableItemGroup, and RequestingVoteTableItemGroup. Each TableItemGrup contains a string SectionName and a List for its corresponding TableItem ...as such:
public class AccountTableItemGroup {
public string SectionName { get; set; }
public List<AccountTableItem> Items
{
get { return this._items; }
set { this._items = value; }
}
public List<AccountTableItem> _items = new List<AccountTableItem>();
public AccountTableItemGroup()
{
}
}
In the future there will be many more TableItemGroups and if they are all the same except for the List part, I don't want to have to copy the code and create a new Group every time and make that small change. I know there must be a better way. I would like to keep using the List<> generics so I don't have to cast anything later though.
The other part are the TableItems. I have AccountTableItem, PendingVoteTableItem, and RequestingVoteTableItem. The TableItems are different from each other, but they each share three common strings -- TitleLabel, DetailLabel, and ImageName. But after that, each TableItem may or may not have additional properties or methods along with it ..as such:
public class AccountTableItem
{
public string TitleLabel { get; set; }
public string DetailLabel { get; set; }
public string ImageName { get; set; }
public bool SwitchSetting { get; set; }
public AccountTableItem()
{
}
}
So my question to all of you is, how do I redefine my class structure to allow for as much reuse of code as possible and to use best coding standards?
I was thinking of having an abstract TableItem class or use an interface for the TableItemGroup? I know that using an interface or an abstract class is best for coding standards, but I don't see how it would cut down on the amount of code I will have?
Thanks a lot for any help.
Abstract away your table item adding necessary fields to the interface or base class:
interface ITableItem // or just a simple or abstract class
{
// common fields go here
}
Then can you make your item group generic with a constraint on generic parameter.
public class ItemGroup<T> where T: ITableItem
{
public string SectionName { get; set; }
public List<T> Items { get; private set; }
public ItemGroup()
{
Items = new List<T>();
}
}
Consider using generics to represent the TableItemGroup container, and make a base class for your TableItem, which you can inherit from for specific types of table item. If you inherit directly from List<T>, then you can treat your item group as a collection without having to use the Items property as in your existing design.
There's not much point in using interfaces for these sorts of types. As they stand they are data classes so have no behavior. If they had behavior, using interfaces would make sense as you would then be able to change implementations and so vary behavior.
public class TableItemGroup<T> : List<T> where T : TableItem
{
public TableItemGroup(string sectionName)
{
SectionName = sectionName;
}
public string SectionName { get; private set; }
}
public class TableItem
{
public string TitleLabel { get; set; }
public string DetailLabel { get; set; }
public string ImageName { get; set; }
}
public class AccountTableItem : TableItem
{
public bool SwitchSetting { get; set; }
}
Now that we have a generic TableItemGroup container, you can re-use this for all TableItem types. Having a base class for TableItem again gives you some re-use.
var items = new TableItemGroup<AccountTableItem>("Accounts");
items.Add(new AccountTableItem { SwitchSetting = true });
Unless you want users to be able to add and remove new lists at will, you should make the setter on the items list protected. Users will still be able to add and remove items, but not create a reference to a new list.

Categories

Resources