Inheriting a List<> in c# and overriding the constructor - c#

I'm trying to create a wrapper around List to do some specific things I want, such as compute max min, extract specific values from some elements, etc.
I start with
public struct datum {
public UInt32[] chan;
public UInt64 sample_number;
public UInt32 time;
public UInt32 source_sector;
}
public class dataSet : List<datum> {
bool dirty=true;
....
}
the methods are typically like this (I want to know if the list has been modified as I have a max()/min() function that only parses the data when it has been modified and caches the values to reuse if the List has not been modified)
public new void Add(datum x ) {
base.Add(x);
this.dirty = true;
}
However, I'm not sure how to create a constructor. This syntax does not work.. how can I get this type of behavior?
public dataSet(int count) {
this = (dataSet) new List<datum>(count);
}
I also have this constructor, which seems to work fine (no compilation errors) though untested
public dataSet(List<datum> data) {
this.AddRange(data);
}
I came across a post that said that you should use a Collection and a List is used for speed. Though I need the speed, and I'm not sure why a Collection would be better?
--UPDATE--
I don't want to use linq as you can't create something that computes max/min simultaneously as efficiently as this:
public void recalculateMaxMin() {
foreach (var d in data) {
for (int i = 0; i < 16; i++) {
if (d.chan[i] > max[i]) max[i] = d.chan[i];
if (d.chan[i] < min[i]) min[i] = d.chan[i];
}
}
}
Thnx

I'm trying to create a wrapper around List to do some specific things I want, such as compute max min, extract specific values from some elements, etc.
Don't. Just use LINQ to Objects. That's what it was designed for:
var list = new List<int> { 10, 20, 30 };
var average = list.Average();
var max = list.Max();
// etc
In general, I would advise against deriving from List<T> anyway - that's not what it was designed for. However, if you must, you just chain from one constructor to a base constructor:
public dataSet(int count) : base(count)
{
// Add in any extra code you want to here. Probably none in this case.
// It would execute *after* the base constructor call.
}
See my article on constructors for more information about constructor chaining.
(I'd also strongly advise you to change the name - dataSet doesn't comply with .NET naming conventions, and DataSet would mean something else entirely to most .NET developers.)

You can never ever set "this" to something in C#. I think you are looking for this:
public dataSet(int count)
: base(count)
{ }
However in my opinion you should take a look at "System.Linq" namespace. I think what you are trying to implement has been done before by Microsoft. 'Select', 'Join', 'Where' and many other clauses has been already implemented in Linq. Also you can use "INotifyCollectionChanged" interface to implement the dirty thing.
Here are some references:
INotifyCollectionChanged
Linq
If you realy need to implement a complete List class with a new behavior, implementing "System.Collections.Generic.IList" interface is the only thing that will rock your idea in an advanced and perfect way. It's more customizable than inheriting from the List class and trying to change everything you have no access to.
Hope it helps
Cheers

public dataSet(int count)
: base(count) {
}

You can call the base type's constructor using base()
public dataSet(int count) : base(count)
{
// no need to implement anything here. base(count) will call the base
// type's constructor
}

Related

Equivalent (or better) C# structures to C++ structures

I am a C++ programmer moving to C# (so complete newb really). So far its a pretty easy transition :)
I am porting some code (well, re-writing it) from C++ to C#. I am stuck with lots of possibilities on how to port the following C++ STL structures. Here is a C++ code snippet of my C++ structure layout (I have not bothered showing the enums to save on clutter, but I can add if required):
struct DeviceConnection_t
{
DeviceType_e device;
DeviceState_e state;
bool isPass;
DeviceConnection_t() :
device(DEV_TYPE_UNKNOWN),
state(DEV_STATE_DISCONNECTED),
isPass(false)
{}
};
struct Given_t
{
std::string text;
std::vector<DeviceConnection_t> deviceConnections;
};
struct Action_t
{
ActionEventType_e type;
uint32_t repeat_interval;
uint32_t repeat_duration;
DeviceType_e device;
bool isDone;
Action_t() :
type(AE_TYPE_UNKNOWN),
repeat_interval(0),
repeat_duration(0),
device(DEV_TYPE_UNKNOWN),
isDone(false)
{}
};
struct When_t
{
std::string text;
std::multimap<uint32_t, Action_t> actions; // time, action
};
So here I have a vector of DeviceConnection_t, which I have read here: c-sharp-equivalent-of-c-vector-with-contiguous-memory can just be made into a C# List<DeviceConnection_t>. That seems to work, so far so good.
Next is my multimap<int, Action_t> where the int is a time value where duplicate entries are expected/allowed.
I read here: multimap-in-net that there is no equivalent in C#, but there are various implementations out there.
So I could use one of these, but other questions I read like: order-list-by-date-and-time-in-string-format got me thinking there might be a better way to achieve what I want.
What I really want is:
1.A list of Action_t in time order - where time could be an element of Action_t (I removed it as a element in my c++ because it became my multi-map key). I also need to be able to search through the collection to find time values.
2. Some sort of default constructor to populate the default values of a newly instantiated struct, but I can't see how this is done either.
I really like the look of the Dictionary C# class, but I don't think that fits any of my requirements at the moment (might be wrong here).
So my two questions are:
What is the best way to create a time ordered collection of objects?
How can I assign default values to a new instance of a structure? (in the same way a default constructor does in C++)?
By using struct, it is impossible to enforce initial values. No explicit default constructor can be provided and in case of default construction, all values will be initialized with their default value. It is only possible to provide additional constructors, where fields can be initialized. In the example, if AE_TYPE_UNKNOWN and DEV_TYPE_UNKNOWN would be 0, then default initialization would actually be equivalent to your values.
struct Action_t
{
// example constructor, but there will always be a default constructor
public Action_t(ActionEventType_e type, DeviceType_e device)
{
this.type = type;
this.device = device;
this.isDone = false;
this.repeat_interval = 0;
this.repeat_duration = 0;
}
public ActionEventType_e type;
public UInt32 repeat_interval;
public UInt32 repeat_duration;
public DeviceType_e device;
public bool isDone;
}
If you need to enforce initialization with values that differ from the default, then you need to create a class, where explicit initialization is possible.
class Action_t
{
public ActionEventType_e type = ActionEventType_e.AE_TYPE_UNKNOWN;
public UInt32 repeat_interval = 0;
public UInt32 repeat_duration = 0;
public DeviceType_e device = DeviceType_e.DEV_TYPE_UNKNOWN;
public bool isDone = false;
}
However, for more flexibility I'd advice to use public properties, either as auto properties or as public properties with private backing field. Depending on your choice and used language standard version, you have different options how to write the properties and the initialization:
class Action_t
{
public Action_t()
{
repeat_interval = 0;
}
public UInt32 repeat_interval { get; set; }
private UInt32 _repeat_duration = 0;
public UInt32 repeat_duration
{
get { return _repeat_duration; }
set { _repeat_duration = value; }
}
public bool isDone { get; set; } = false; // valid for C# 6
}
You should read into the differences between struct and class in C#, since there are some mayor differences that you may not expect as a C++ programmer, where struct is basically a public-default class. Then decide, if struct is suited for your case.
The best equivalent to a sorted multimap would probably be a SortedDictionary<key, ICollection<values>> with an add method that handles new keys / adding to existing keys.
IDictionary<DateTime, ICollection<Action_t>> actions = new SortedDictionary<DateTime, ICollection<Action_t>>();
void AddAction(DateTime key, Action_t action)
{
ICollection<Action_t> values;
if (!actions.TryGetValue(key, out values))
{
values = new List<Action_t>();
actions[key] = values;
}
values.Add(action);
}
Unfortunately C# doesn't seem to have a sorted List. The Dictionary is fine if you have Key, Value pairs.
1) If its just a collection (List) you can take a look at the discussion here:
Is there a SortedList<T> class in .NET?. Otherwise you can manually sort the collection(I named it sort in my example) like:
actions.Sort((x, y) => x.time.CompareTo(y.time));
In this your time object should be a IComparable or a primitive, but you can replace "x.time.CompareTo" to any other sorting method. (Based on: List<> OrderBy Alphabetical Order).
If you use a list you can just search the collection with linq:
actions.First(x=>x.time.certainValue == DesiredValue);
But there are many functions to search through the tree. There are some displayed: https://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods(v=vs.110).aspx
2) There are multiple ways to do this. First off, the default constructor:
Action_t() {
type=AE_TYPE_UNKNOWN;
repeat_interval=0;
repeat_duration=0;
device= DEV_TYPE_UNKNOWN);
isDone = false;
}
This works like any other code. But if all values are public Properties (Also a variable: https://msdn.microsoft.com/nl-nl/library/x9fsa0sw.aspx) then you can remove the constructor (or have a public one that you can access) and create new instances with:
new Action_t {
type=AE_TYPE_UNKNOWN,
repeat_interval=0,
repeat_duration=0,
device= DEV_TYPE_UNKNOWN),
isDone = false
}
The difference is where the variables are set. The default constructor is always safe.
I hope this answers your question!

Effects of returning a self reference from an instance method in C#

Let's say I have an interface called IConvertableModel and it helps me to convert some MVC models to/from DTO objects as shown below:
public class DisplayEditModel : IConvertableModel<Display>
{
[HiddenInput(DisplayValue = false)]
public int ObjectId { get; set; }
[StringLength(255)]
public string Description { get; set; }
public Display ToDto()
{
return new Display
{
Description = Description,
ObjectId = ObjectId,
};
}
public void SetFromDto(Display dto)
{
Description = dto.Description;
ObjectId = dto.ObjectId;
}
}
But there is one problem with this approach and that is it doesn't allow me do this :
var dto = _dtoRepository.GetFirstDto();
return new DisplayEditModel().SetFromDto(dto);
Instead I should do the following:
var dto = _dtoRepository.GetFirstDto();
var model = new DisplayEditModel();
model.SetFromDto(dto);
return model;
and this is adding extra two lines of code and little bit complexity in the long run.
What I am thinking is to convert SetFromDto method to something like this:
public DisplayEditModel SetFromDto(Display dto)
{
Description = dto.Description;
ObjectId = dto.ObjectId;
return this;
}
I think the benefit of this code is obvious but I also like to learn whether this harms code readability and leads to unexpected results for developers in the long run and if you think anything else, what would you recommend.
Note: Because of the interfaces reasons, I am not thinking to implement a constructor method.
A few thoughts, to begin with:
Adding lines of code is not the same as adding complexity. Having three statements, where each does a simple operation, is not necessarily harder to maintain or understand than a single statement with three operations inside of it.
When a method that begins with Set..., programmers will automatically assume that some stateful values of the target object are going to be changed by this method. It is rare for Set methods to have a return value. Property setters in C# actually "return" the original value passed into them, so you can chain setters:
int i = foo.A = 2;
So the precedent is generally against returning "this" from a set method specifically.
Chaining in general is most useful/desired when you're expecting several operations to be performed, one after the other. For example, C# provides nice initialization syntax so you can "chain" a bunch of different property setters on the same object:
var foo = new Foo { A = 1, B = 2 };
You can see how chaining is fulfilling the need to perform similar, grouped, repetitive operations that typically get performed all together. That is not the problem that you are trying to solve.
If your main gripe is that you don't like having three lines of code, why not just use a helper whose name indicates what you're trying to do?
TModel MapToModel<TModel, TDto>(TDto dto, TModel model)
where TModel : IConvertableModel<TDto>
{
model.SetFromDto(dto);
return model;
}
// usage:
var dto = _dtoRepository.GetFirstDto();
return MapToModel(dto, new DisplayEditModel());
... or even:
TModel CreateModel<TModel, TDto>(TDto dto)
where TModel : IConvertableModel<TDto>, new()
{
var model = new TModel();
return MapToModel(dto, model);
}
// usage:
var dto = _dtoRepository.GetFirstDto();
return CreateModel<DisplayEditModel>(dto);
This is simple, readable, and feasible, whereas the approach you're suggesting would break the IConvertableModel<Display> interface:
public interface IConvertableModel<TDto>
{
public TDto ToDto();
public ??? SetFromDto(TDto dto);
}
What would SetFromDto return? You would have to define another generic type on IConvertableModel.
public interface IConvertableModel<TDto, TModel> {
public TDto ToDto();
public TModel SetFromDto(TDto dto);
}
But this wouldn't really indicate that the SetFromDto method is necessarily returning itself, because it allows for a class that is not a TModel to implement IConvertableModel to convert between two other types.
Now, you could go out of your way to push the generics even farther:
public interface IConvertableModel<TDto, TModel>
where TModel : IConvertableModel<TDto, TModel>
{...}
But this still allows for some fudging, and the interface cannot guarantee that you are really returning "this" object. All in all, I'm not a big fan of that approach.
Rather than having DisplayEditModel have a get/set method for a Display object to get/set the values, just use a property that doesn't actually have a separate backing store:
public Display Display
{
get
{
return new Display
{
Description = Description,
ObjectId = ObjectId,
};
}
set
{
Description = value.Description;
ObjectId = value.ObjectId;
}
}
Now you can use an object initializer with this property when creating a model:
return new DisplayEditModel() { Display = dto };
This is a very javascript way of approaching this problem, though it has it's benefits. In the context of C#, it is a little bit strange though libraries such as LINQ do this to allow chaining together function calls.
My only worry about this, is that this has to be a class that does this consistently. Implementing a chaining function return pattern is not really a convenience as much as it is a design choice. The rule to follow in this case, would be to return this every time you mutate the object.
Chaining also may not be worth it performance wise. Something that can be done by wrapping all those operations into a single function is much faster. For instance:
MyVector.setX(1).SetY(1).SetZ(1).SetW(0)
is a lot slower than simply
MyVector.set(1, 1, 1, 0)
because now you are now doing excessive stack operations to do something fairly simple. It only becomes worth it on very large operations that take up the bulk of the computing time and make sense to chain together. For this reason, LINQ allows you to chain things together.
I wouldn't say that it necessary "harms" or is dangerous. We are in the world of a managed language, so we don't have direct access to that memory location (unlike C/C++). So I would just call it a design choice which can be fairly powerful in some cases and not so much in others.
As noted, chainable methods work fine but are not as common in C# as in some other languages. If the extra lines of code only happen in one place, I'd just leave it alone. If it's really bugging you or you do it a lot, then consider implementing a special constructor for it:
public void DisplayEditModel(Display dto)
{
this.SetFrom(dto);
}
or a static factory method:
public static DisplayEditModel CreateFrom(Display dto)
{
var model = new DisplayEditModel();
model.SetFrom(dto);
return model;
}
Either option has a clear intent, lets you create and return the object in a single line, and is idiomatic. It does require a few extra lines of code in DisplayEditModel, but I doubt it will be a serious problem.

C# type argument constraints

I'm trying to do something a certain way... but I'm certain there's a better way
public interface IMix
{
T Mix<T>(List<T> values) where T : IMix;
}
The problem with this is that if I want to "Mix" 5 values, then I need to do value1.Mix(others) but that is not clean. Plus, the type of T needs to be the same type as whatever class implements the interface. So, this doesn't really work.
I was thinking something like this:
public static class MixWrapper
{
public static T Mix<T>(List<T> values);
}
But that obviously won't work because I have to define the body in MixWrapper
EDIT: to clear up some misunderstanding, these are not real math averages, I could just as easily say "Fuse" or anything else. For example I could be trying to "average" a list some struct or other class.
EDIT 2:
One example could be a class like this
class Sequence : IMix
{
List<int> sequence;
double period;
double weight;
}
The "Mix" in this case would need to return a Sequence that was built this way: the resulting period is the weighted average of the periods based on the weight. The weight is the sum of the weights, and the sequence is the weighted average of the sequences after they have been timescaled down to the resulting period. Suffice to say, any complicated method that you could think of needs to be accounted for
If you want to calculate average of some list, then you can use LINQ:
var value = list.Average(x => x.SomeProperty);
Put the type T on your interface and just fill it with the same type as the class when you're implementing it:
public interface IMix<T>
{
T Mix(List<T> values);
}
public class ConcreteObjects : IMix<ConcreteObjects>
{
public ConcreteObjects Mix(List<ConcreteObjects> values)
{
// do mixing
}
}
This also leaves the door open for other classes to be able to mix ConcreteObjects if need be.
I think you're looking for an extension method.
You need to define a static method somewhere (some helper class, I suppose) like this:
public static T Average<T>(this List<T> list) where T : IAverage
{
return // average stuff
}
Now you just need to include your helper class with using and you can do something like this:
AverageClass implements IAverage
List<IAverage> list = new List<AverageClass>();
var average = list.Average();

Delegated - is correct my usage of delegates?

I created a class where the main task is get data from the DB and mapping it to some object. The problem is the same class needs to map different datareader to different object. So, what I tried to do is to get out the mapping method using delegates.
Here is part of my code. See the important rows in bold.
public class GetDetails<T>
{
**public delegate void DelegateMapping(T position, IDataReader reader);**
**public DelegateMapping mappingMethod;**
public T Get(T instance)
{
//Get IDs and Add to list
_db.ExecuteReader(storedProcedure.ToString(), CommandType.StoredProcedure, reader =>
{
while ( reader.Read() )
{
**mappingMethod(instance, reader);**
}
}, parameterList.ToArray());
return instance;
}
}
And this is the class which is calling and using the "GetDetails" class
public class PositionDB : DbBase
{
public Position GetPositionDetails(string IDs)
{
GetDetails<Position> getIDs = new GetDetails<Position>(base.db);
getIDs.storedProcedure = StoredProcedure.NET_ADM_GetPositionDetails;
//Set the Delegated Method
**getIDs.mappingMethod = MappingPositionDetails;**
//Set Parameters
getIDs.parameterList.AddInParam("PositionIds", DbType.String, IDs);
//Return the PositionId Collection
return getIDs.Get(new Position());
}
**private void MappingPositionDetails(Position position, IDataReader reader)
{
position.Id = reader["CompPositionId"];
position.Description = reader["Description"];
position.ExpirationDate = reader["ExpirationDate"];
position.Title = reader["Title"];
}**
}
The code is working OK.
The questios are:
Did I use delegate correctly?
This kind of solution can cause problems in the future (performance)?
There is another better solution?
Thank you very much
Sebastian
To specifically answer your questions:
Yes, you did use delegates correctly
Yes, it can cause problems due to concurrency issues while multithreading
I think so, I detailed one possible solution below
I would propose three changes:
Move the delegate call into the method (concurrency issues, one thread could change the mapping delegate while another thread tries to access it, now trying to map a reader to completely different object than provided)
Use the already present generic Action/Func delegates, no need to define your own.
Use lambda expressions to define the mapping, no need for extra methods
Notice: 2 and 3 will need at least .net 3.5.
Employing these two proposals, your code would look like this:
public class GetDetails<T>
{
public T Get (T instance, Action<T, IDataReader> mappingMethod)
{
//Get IDs and Add to list
_db.ExecuteReader(storedProcedure.ToString(), CommandType.StoredProcedure, reader =>
{
while ( reader.Read() )
{
mappingMethod(instance, reader);
}
}, parameterList.ToArray());
return instance;
}
}
Now you can use this method in a multi-threaded environment as well.
Edit
just realized it's just part of the code. I corrected my proposal to take this into account.
Yes (There's some improvements you could make, see 3)
Not performance wise, maybe some issues in discoverability.
I would use polymorphism to eliminate the delegate completely for discoerability. Perhaps using an abstract method/class. Also depending on which .NET version you're developing for you can use lambdas and simpler types.
public Action<Position, IDataReader> Mapping { get; set; }
Then
getIDs.Mapping = (position, reader) =>
{
position.Id = reader["CompPositionId"];
position.Description = reader["Description"];
position.ExpirationDate = reader["ExpirationDate"];
position.Title = reader["Title"];
};

Generic Linked List

Before posting my question, I would like to tell you that I have no prior experience in .Net technologies and have recently started to learn C# (and WPF). My company is looking to move onto .Net technologies and I am the only one in my team learning it, so have noone apart from you guys to discuss or ask something. So if my questions are too stupid or basic at best, please bear with me.
I was trying to create a generic linked list class to allow creation of linked lists of different types. I wrote the following code and would like to have your advise on whether I have written this code properly or not. Any suggestions to improve the code in any way is most welcome.
Main program
class Program
{
static void Main(string[] args)
{
GenLinkedList<string> list = new GenLinkedList<string>("abc");
list.AddtoList("def");
int i = 0;
string[] arr = new string[10];
list.LinkedList.CopyTo(arr,0);
for (i = 0; i < list.LinkedList.Count; i++)
{
Console.WriteLine(arr[i]);
}
GenLinkedList<int> listInt = new GenLinkedList<int>(1);
listInt.AddtoList(2);
i = 0;
int[] arrInt = new int[10];
listInt.LinkedList.CopyTo(arrInt, 0);
for (i = 0; i < listInt.LinkedList.Count; i++)
{
Console.WriteLine(arrInt[i]);
}
}
}
Class GenLinkedList
public class GenLinkedList<T>
{
private LinkedList<T> _linkedlist;
public GenLinkedList(T a)
{
_linkedlist = new LinkedList<T>();
_linkedlist.AddLast(a);
}
public LinkedList<T> LinkedList
{
get
{
return _linkedlist;
}
}
public void AddtoList(T a)
{
LinkedList.AddLast(a);
}
}
Why not use System.Collections.Generic.LinkedList<T>? You're using it internally in your GenLinkedList<T> already and it's already Generic for you.
It's the Framework Provided Generic Doubly Linked List implementation. Read up on it at:
MSDN - LinkedList(T) Class
If you're creating a Generic Linked List as an exercise, you shouldn't base your implementation of of an existing Generic Linked List. You're really not going to be learning anything by wrapping something that already does exactly what you need to do.
1
A generic linked list implementation already exists in the .NET framework: LinkedList<T>. But you already know that; your code wraps it.
2
OK, so you know that. Why would you wrap it, then? The only functionality you appear to have implemented is AddtoList, which doesn't do anything the LinkedList<T> doesn't already do itself (after all, this is only a thin wrapper around LinkedList<T>.AddLast). What this means is that your GenLinkedList<T> class really doesn't offer the functionality of a linked list; it's basically an add-only collection (which could just as easily have been implemented with a List<T>, or a Stack<T>, or a Queue<T> -- anything, really).
3
Assuming you do have a good reason to wrap a LinkedList<T> (e.g., you're planning to add more functionality down the line that would actually leverage the behavior of a LinkedList<T> and/or -- here's a key ingredient -- you want to restrict the way calling code is able to interact with the list (e.g., no removals)), you really shouldn't expose your LinkedList<T> member at all. The purpose of a wrapper is just that: to wrap. You take an existing class and basically give it a new kind of interface. By exposing the underlying object directly, you cripple your wrapper. Any additional restrictions/validation/logic you have in your wrapper can be bypassed.
So, for example, if you want to be able to copy your list to an array, instead of doing this:
list.LinkedList.CopyTo(arr,0);
You would implement a CopyTo method within your GenLinkedList<T> class (which could simply call _linkedlist.CopyTo) and use that.
But I really think the first question you should be asking yourself is what you want to accomplish by wrapping LinkedList<T> in the first place.
The obvious question is why you don't just use LinkedList<T> directly, although it looks like you're trying to emulate a singly-linked list.
In this case, you should avoid exposing the underlying LinkedList<T> instance, since any client could manipulate it directly. I would also implement IEnumerable<T> which will make your list usable by linq.
I got this from http://msdn.microsoft.com/en-us/library/0x6a29h6.aspx
Works fine with me.
namespace GenLinkedList
{
class Program
{
static void Main(string[] args)
{
GenericList<object> list = new GenericList<object>();
// Add items to list.
list.AddHead("some string here");
list.AddHead(DateTime.Today.ToLongDateString());
list.AddHead(13);
list.AddHead(13.005);
for (int x = 0; x < 10; x++)
{
list.AddHead(x);
}
// Enumerate list.
foreach (object i in list)
{
Console.WriteLine(i + " " + i.GetType());
}
Console.WriteLine("\nDone");
}
}
}
namespace GenLinkedList
{
// type parameter T in angle brackets
class GenericList<T>
{
// The nested class is also generic on T.
public class Node
{
private Node next;
// T as private member data type.
private T data;
// T used in non-generic constructor.
public Node(T t)
{
next = null;
data = t;
}
public Node Next
{
get { return next; }
set { next = value; }
}
public T Data
{
get { return data; }
set { data = value; }
}
}
private Node head;
// constructor
public GenericList()
{
head = null;
}
// T as method parameter type
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
}
public IEnumerator<T> GetEnumerator()
{
Node current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
}
}

Categories