Reputation: 1989
Currently i have a class which has only properties
class MyEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
In my other class, I use to set the values like
MyEntity objEnt = new MyEntity();
objEnt.FirstName="abc";
objEnt.LastName = "edf";
The reason i have the class MyEntity
with only properties is to ensure adherence.
Question here is, if this approach is correct? I can have multiple instances of MyEntity
Can i use Static Class for this? How can i use Generics in this?
BTW the implementation is in C#
Thanks in advance
Cheers,
Karthik
Upvotes: 0
Views: 110
Reputation: 23
Here is a quick and dirty use of generics for your unspecified DTO I am assuming.
class MyEntity<T>
{
public T value { get; set; }
}
Upvotes: 0
Reputation: 49974
I had an answer half typed, but then Jon answered so my answer in its current form became pointless....
I will offer a counterpoint on Jon's answer though. Think carefully before using immutable objects - they are good from some perspectives, but you will quickly run into trouble if using them for binding to editable fields, or if serializing them (either to storage or for transferring, ie WCF web service calls).
Upvotes: 0
Reputation: 16577
As already said it depends from your needs. Just to note that you can't use static class as you want to have multiple instances and also there can be issues with synchronization while access from multiple threads.
As for generics ... whats for you need it here ?
Upvotes: 1
Reputation: 1499770
Personally I prefer types to be immutable where possible - for example by giving MyEntity
a constructor with two parameters, and removing the public setters from the properties. (Whether you keep private setters which you just don't use outside the constructor, or move to "proper" readonly fields and readonly properties is another choice.) However this mutable type may be absolutely fine for you - it's impossible to say without knowing what you're trying to do.
Note that you can use object initializers to make your initialization simpler, while you're using the mutable type:
MyEntity objEnt = new MyEntity { FirstName = "abc", LastName = "edf" };
(If you made the type immutable, you'd pass the values in the constructor. You could still use names via C# 4's "named arguments" feature, if you're using C# 4.)
Upvotes: 1