best way to create object - c#

This seems to be very stupid and rudimentary question, but i tried to google it, but couldn't a find a satisfactory answer,
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(){}
public Person(string name, int age)
{
Name = name;
Age = age;
}
//Other properties, methods, events...
}
My question is if i have class like this, what is the best way to create an object?
Person p=new Person("abc",15)
OR
Person p=new Person();
p.Name="abc";
p.Age=15;
What is the difference between these two methods and what is the best way to create objects?

Decide if you need an immutable object or not.
If you put public properties in your class, the state of every instance can be changed at every time in your code. So your class could be like this:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(){}
public Person(string name, int age)
{
Name = name;
Age = age;
}
//Other properties, methods, events...
}
In that case, having a Person(string name, int age) constructor is not so useful.
The second option is to implement an immutable type. For example:
public class Person
{
public string Name { get; private set; }
public int Age { get; private set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
//Other properties, methods, events...
}
Now you have a constructor that sets the state for the instance, once, at creation time. Note that now setters for properties are private, so you can't change the state after your object is instantiated.
A best practice is to define classes as immutable every time if possible. To understand advantages of immutable classes I suggest you read this article.

Really depends on your requirement, although lately I have seen a trend for classes with at least one bare constructor defined.
The upside of posting your parameters in via constructor is that you know those values can be relied on after instantiation. The downside is that you'll need to put more work in with any library that expects to be able to create objects with a bare constructor.
My personal preference is to go with a bare constructor and set any properties as part of the declaration.
Person p=new Person()
{
Name = "Han Solo",
Age = 39
};
This gets around the "class lacks bare constructor" problem, plus reduces maintenance ( I can set more things without changing the constructor ).

There's not really a best way. Both are quite the same, unless you want to do some additional processing using the parameters passed to the constructor during initialization or if you want to ensure a coherent state just after calling the constructor. If it is the case, prefer the first one.
But for readability/maintainability reasons, avoid creating constructors with too many parameters.
In this case, both will do.

In my humble opinion, this is just a matter of deciding if the arguments are optional or not. If an Person object shouldn't (logically) exist without Name and Age, they should be mandatory in the constructor. If they are optional, (i.e. their absence is not a threat to the good functioning of the object), use the setters.
Here's a quote from Symfony's docs on constructor injection:
There are several advantages to using constructor injection:
If the dependency is a requirement and the class cannot work without it then injecting it via the constructor ensures it is present when the class is used as the class cannot be constructed without it.
The constructor is only ever called once when the object is created, so you can be sure that the dependency will not change during the object's lifetime.
These advantages do mean that constructor injection is not suitable for working with optional dependencies. It is also more difficult to use in combination with class hierarchies: if a class uses constructor injection then extending it and overriding the constructor becomes problematic.
(Symfony is one of the most popular and respected php frameworks)

If you think less code means more efficient, so using construct function is better.
You also can use code like:
Person p=new Person(){
Name='abc',
Age=15
}

how about
var obj = new {ID = 1, Price = 2};

Depends on your requirment, but the most effective way to create is:
Product obj = new Product
{
ID = 21,
Price = 200,
Category = "XY",
Name = "SKR",
};

Or you can use a data file to put many person objects in to a list or array. You do need to use the System.IO for this. And you need a data file which contains all the information about the objects.
A method for it would look something like this:
static void ReadFile()
{
using(StreamWriter writer = new StreamWriter(#"Data.csv"))
{
string line = null;
line = reader.ReadLine();
while(null!= (line = reader.ReadLine())
{
string[] values = line.Split(',');
string name = values[0];
int age = int.Parse(values[1]);
}
Person person = new Person(name, age);
}
}

Related

Should I use multiple constructors or an interface?

I have a class called Package, in this class I have around 10 attributes, let's call them 1,2,3,4.. etc to 10. The types of these attributes are strings, ints and some DateTimes. When making a new object of Package sometimes I just need attribute 1, sometimes I need 5, 6 and 9, and sometimes I need 3 and 10 etc.
So just two examples: new Package("bla", "bla bla",100) or new Package(2983)
I've read:
An interface looks like a class, but has no implementation. The only
thing it contains are declarations of events, indexers, methods and/or
properties. The reason interfaces only provide declarations is because
they are inherited by classes and structs, which must provide an
implementation for each interface member declared.
Since there are no other methods in the class and just a constructor and attributes, is it better to use like 20 constructors or should I make an interface for this situation?
EDIT:
I should've probably mentioned that I also have some enums to 'kind of' determine what kind of Package it is.
An interface doesn't help you in any way here.
If you want to force that specific variables are filled in together, like 1, 2 and 3 should always be filled together but in another case just 4 is enough, you could use separate constructors, or static methods with helpful names that create the objects (like CreateFromId, CreateFromNameAndAge).
If you don't care at all, you can simply make a parameterless constructor (or a constructor with optional fields) and set the fields required with object initializers:
var x = new Class() { Field1 = 1, Field2 = "2" };
Maybe this is a sign you are doing too much in a single object, but without actual information about your class design, we can't tell that much.
Inheritance seems to be a decent solution here too, if the packages have distinct uses (like ProductPackage, PersonPackage, etc.). The shared properties reside in the base class, and all specific properties can reside in the deriving classes.
Constructors provide guidelines as to how can an object be created. Assuming that by using an interface you mean specify the properties which need to exist, you are not giving any guidelines as to how properties need to be initialized.
Having multiple constructors should be better since you are providing means in which users can instantiate your objects. This will allow you to initialize your other parameters accordingly.
You could still use an interface if you require to stipulate what fields need to exist.
Besides above points, consider using Builder pattern - https://en.wikipedia.org/wiki/Builder_pattern
Here is the example:
class Package
{
public string Name { get; set; }
public string Description { get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public static PackageBuilder Create()
{
return new PackageBuilder(new Package());
}
}
class PackageBuilder
{
private readonly Package _package;
public PackageBuilder(Package package)
{
_package = package;
}
public PackageBuilder WithName(string name)
{
_package.Name = name;
return this;
}
public PackageBuilder WithDescription(string description)
{
_package.Description = description;
return this;
}
public PackageBuilder Prop1(string prop)
{
_package.Prop1 = prop;
return this;
}
public PackageBuilder Prop2(string prop)
{
_package.Prop2 = prop;
return this;
}
public static implicit operator Package(PackageBuilder pb)
{
return pb._package;
}
}
class Client
{
Package BuildPackage()
{
var package =
Package.Create().WithName("My Package").WithDescription("Description").Prop1("foo").Prop2("bar");
return package;
}
}

C# Constructor Use Private/Public Fields [duplicate]

This question already has answers here:
OO Design - do you use public properties or private fields internally? [duplicate]
(10 answers)
Closed 9 years ago.
class Student
{
private string firstName;
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value; // Possible logical checks may be implemented here in the future
}
}
public Student (firstName)
{
this.firstName = firstName; // Option 1
// Or
FirstName = firstName; // Option 2
}
}
which of the two lines is more standard?
do we use the private or the public members in the constructor?
You could go with option 3
public string FirstName {get; set;}
public Student (firstName)
{
FirstName = firstName;
}
It depends... Often on things not included in your example. For one thing, your entire property can be shortened to an auto-implemented property:
public string FirstName { get; set; }
Which would make the question moot in this case. Beyond that, the question comes down to what sort of logic may exist (now or in the future) in the property and whether or not that logic needs to be invoked by the constructor.
For example, does the property internally check for a required value or perform some other validation? Something like this:
private string firstName;
public string FirstName
{
get { return firstName; }
set
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentNullException("FirstName");
firstName = value;
}
}
In a case like this clearly you'd want the constructor to use the property and not the backing field so that the logic is applied when constructing the object.
Conversely, you might have logic that should only be used when accessing the setter but not when constructing the object. Off the top of my head one example might be an object which maintains information about a Location. It might have an Address property and a Coordinates property, and any time one of them changes there is a back-end process to geolocate the new value and update the other. But you might have a constructor which accepts both (perhaps when re-building an existing Location from a database) and it wouldn't make sense to perform the geolocation during construction. In that case you'd set the backing fields and not the properties.
For lack of a compelling reason not to use the properties, I'd generally prefer to use them instead of the backing fields. Simply because logic might be added to those properties later that all accessors should use. I also find it more likely that the properties have a more meaningful name than backing fields (for example, FirstName is more readable/meaningful than _firstName) so the preference would be to keep the rest of the code as readable as possible and to prefer more readable names.
It is a stylistic choice that doesn't really matter. Personally, I use the public property name, because I like to use auto properties, and that is the only option in that case. Using the public property keeps my code consistent.
When I am writing POCOs (Plain Old CLR Objects) where things are trivial, I go with this approach:
public class POCO
{
public POCO()
{
Name = "Moo-Juice";
}
public string Name { get; set; }
}
In non-trivial cases where I actually need the member variable, I prefix it with _ (this helps in intellisense, believe me - and allows you to distinguish between members and locals):
public class NonTrivial
{
private string _name;
public NonTrivial()
{
_name = "Jon Skeet"; // He is non-trivial
}
}
This way I avoid polluting my code with this. everywhere.
It depends:
private string firstName;
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = (value=="mycheck")?"default":value;
}
}
If your property has some validations then you should go for:
public Student (firstName)
{
FirstName = firstName;
}
The most common is to use the property, but it is a matter of choice.
In this case particularly, you should use automatic property:
public string FirstName { get; set; }
And the compiler adds the backing field automatically.
You can also choose to not add the parameter constructor, as since C# 3.5 (IIRC), you can use automatic initializers:
new Studant() { FirstName = "John Doe" }
Which calls the constructor, and sets the property in one line.
Overall, I tend to only request a constructor parameter for things it really depend on (see: dependency injection), and let the not always needed ones optional until they are required, like validating before persisting.

How to define named Parameters C#

This seems like a simple question, but for some reason I can't find the answer anywhere. Basically, I'd like to be able to implement a constructor that takes NamedParameters.
By named parameters, I do not mean parameters with default values (optional parameters) such as:
public SomeMethod(){
string newBar = Foo(bar2 : "customBar2");
}
public string Foo(string bar1 = "bar1", bar2 = "bar2" ){
//...
}
A good example of what I'm trying to achieve is the AuthorizeAttribute from the System.Web.Mvc assembly. Which you can use the following way:
[Authorize(Roles = "Administrators", Users = "ThatCoolGuy")]
public ActionResult Admin(){
}
The constructor's signature in intellisense looks like the following example and I believe (please confirm) that those NamedParameters are mapping to class properties.
AuthorizeAttribute.AuthorizeAttribute(NamedParameters...)
Initiliaze new instance of the System.Web.Mvc.AuthorizeAttribute class
Named parameters:
Order int
Users string
Roles string
Please note:
The syntax of defining the parameter name when calling a method has nothing to do with optional parameters:
You can use Foo(bar1 : "customBar1"); even if Foo is declared like this: void Foo(string bar1)
To answer the question:
My guess is that this is syntactic sugar similar to the object initializers introduced in Visual Studio 2010 and therefore you can't use this for your own classes.
The behaviour you are talking about is specific for attributes and cannot be reused in "normal" classes constructors.
You don't need to "implement" anything.
The parameters can be used in the manner you describe just by existing as parameters on the constructor.
You do need to be using C# 3.5 or above, when they were introduced.
Your example will compile and run on C# 4.0 / Visual Studio 2010 without modification.
See Named and Optional Arguments (C# Programming Guide) on MSDN.
In regards to properties on the object, that do not have a corresponding constructor arguments, the exact syntax is specific to attributes and can't be replicated, though, with object initializers you can get close.
You can use the builder/constructor info pattern together with property initializers.
class PersonInfo
{
public string Name { get; set; }
public int? Age { get; set; }
public Color? FavoriteColor { get; set; }
public Person BuildPerson()
{
return new Person(this);
}
}
class Person
{
public Person(PersonInfo info)
{
// use info and handle optional/nullable parameters to initialize person
}
...
}
var p = new Person(new PersonInfo { Name = "Peter", Age = 15 });
// yet better
var p = new PersonInfo { Name = "Peter", Age = 15 }.BuildPerson();
I however don't understand, why you don't just use named parameters and provide null for indicating optional parameters.
class Person
{
public Person(string name = null, int? age = null, Color? favoriteColor = null) { /* ... */ }
}
var p = new Person(name: "Peter", age: 15);
Named parameters are NOT specific to attributes. It's a language syntax that can be used everywhere. It's fine to use properties for initialisers but you don't always want to have internals set as set properties.
Just instantiate you class using:
TheClass c = new Theclass(param3:firstValue, param1:secondValue, param2:secondValue);
With regards to this part of the question:
"I however don't understand, why you don't just use named parameters and provide null for indicating optional parameters."
The reason named parameters are nice is you don't need to provide extraneous values in parentheses, just what you want to specify, because if it's optional you shouldn't even need to put null. Furthermore, if you specify null, you are overriding any default value for that parameter which makes it optional. Being optional implies there's a default value meaning nothing passed in.
Property initialisation at instance time is purely there for convenience. Since C there has been the ability to initialise values at construction time on types. Which is handy if those values can't be specified in the constructor. I personally feel that the convenience of them has spoiled people and it get a little too liberal and make everything public get AND set. Just depends on the design and security of properties you need.
I doubt that's possible. This is something specific for attributes.
I think the closest option is to use an object initializer:
class Foo {
public string Name {get;set;}
public int Data {get;set;}
}
var foo = new Foo {Name = "MyName", Data = 12};
try to use this signature
[AttributeUsage(AttributeTargets.Class)]
before the name of your class
Please refer to MSDN specification for full description:
https://msdn.microsoft.com/en-us/library/aa664614(v=vs.71).aspx
"Each non-static public read-write field and property for an attribute class defines a named parameter for the attribute class".
Visual C# 2010 introduces named and optional arguments. Named argument able you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list.Named arguments free you from the need to remember or to look up the order of parameters in the parameter lists of called methods.
static void Main(string[] args)
{
mapingFunction(snum2: "www.stackoverflow.com", num1: 1);
}
public static void mapingFunction(int num1, string snum2)
{
Console.WriteLine(num1 + " and " + snum2);
}
here you can see that argument are passed with our their order
What you probably want to do is implement public properties in your attribute:
public class AuditFilterAttribute : ActionFilterAttribute
{
public string Message { get; set; }
public AuditFilterAttribute() { }
}
They can be accessed through Named Parameters where you apply it:
[AuditFilter(Message = "Deleting user")]
public ActionResult DeleteUser(int userId)
Hope that helps...

C# Primitive Types or Complex Types as Method Signatures?

What are the pros and cons of using Primitve Types or Complex Types?
When should you use primitive types over complex types and vice versa?
i.e.:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public int IQ { get; set; }
}
public void FooPrimitiveTypes (string firstName, string lastName, int age, int IQ)
{
}
public void FooComplexTypes(Person person)
{
}
To pass each property separately are generally used when you are dealing with disjoint values. Also, sometimes used on constructors. Bad practice.
This way is preferred when the values are related.
Why #1 is a bad practice - suppose you needed to add height. I'd much rather update one class by adding another property, instead of 50 methods.
Does Foo conceptually deal with a Person? Does all (or at least most) of Person get used by Foo, or is it just using a few bits of information that happen to be in Person? Is Foo likely to ever deal with something that's not a Person? If Foo is InsertPersonIntoDB(), then it's probably best to deal with Person.
If Foo is PrintName(), then maybe PrintName(string FirstName, string LastName) is more appropriate (or alternatively, you might define a Name class instead and say that a person has a Name).
If you find yourself creating half initialized temporary Person objects just to pass to Foo, then you probably want to break down the parameters.
Something to note is that when you use primitives they are being passed by value... the object reference is also being passed by value but since all the underlying references to the values are references it is effectively pass by reference. So depending on what you are doing this pass by value or pass by reference could be of importance. Also in the first case modifications to the primitives will not affect the values of the variables in the calling scope however modifying the object passed in will affect the object in the calling scope.

Good class design by example

I am trying to work out the best way to design a class that has its properties persisted in a database. Let's take a basic example of a Person. To create a new person and place it in the database, I want the DateOfBirth property to be optional (i.e. NULLable in the DB).
Here's my sample code:
namespace BusinessLayer
{
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
}
I'm unsure as to whether the fields should be public or not. Should I do it like this:
class Program
{
static void Main(string[] args)
{
Person person1 = new Person("Kate","Middleton",null);
}
}
or like this:
class Program
{
static void Main(string[] args)
{
Person person1 = new Person();
person1.FirstName = "Kate";
person1.LastName = "Middleton";
}
}
I'm also wondering how I should be dealing with the optional properties of the class. Once the fields have been populated how do I then save them to the DB? I have a DatabaseComponenet class to save the information. How do I deal with the optional when saving to the database?
So, would I do something like this:
public int Save()
{
int personId;
personId = DatabaseComponent.InsertPerson(FirstName, LastName, DateOfBirth);
return personId;
}
Thanks for any help! Some useful URLs on good class design would also be appreciated.
First, I'd put two distinct public constructor to Person:
namespace BusinessLayer
{
class Person
{
public Person(string firstName, string lastName): this(firstName, lastName, DateTime.Now)
{}
public Person(string firstName, string lastName, DateTime birthDate)
{
FirstName = firstName;
LastName = lastName;
DateOfBirth = birthDate;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
}
this allows you to write both
var p = new Person("Marilyin", "Manson");
var p2 = new Person("Alice", "Cooper", new DateTime(...));
and
var p = new Person { FirstName="Marilyn", LastName="Manson" };
I can't see why you should limit to only one form.
As for the DatabaseComponent I'd strongly suggest to write a method that allows you to save a Person instead of the signature you are implicitly declaring.
That's because, should one day change the way a Person is defined, you'd probably have to change the code in each point you invoke Save() method. By saving just a Person, you only have to change the Save() implementation.
Don't you plan to use an ORM by the way?
With C# 3.0 class initializers I no longer bother of providing a constructor that allows me to initialize all properties:
var person1 = new Person
{
FirstName = "Kate";
LastName = "Middleton";
};
As far as the Save method is concerned I usually put them in a separate repository class:
public int Save(Person person)
{
...
}
and then when I need to save a person I do:
var person1 = new Person
{
FirstName = "Kate";
LastName = "Middleton";
};
var id = new PersonsRepository().Save(person1);
Only use constructors if some fields are mandatory since it's an effective way to make sure that those fields are specified.
I'm unsure as to whether the fields should be public or not
Fields usually means member variables and those should always be private. As for properties I would stick with get/set for database objects.
I'm also wondering how I should be dealing with the optional properties of the class. Once the fields have been populated how do I then save them to the DB?
Saving things to the database is a whole different story. I would not try to invent my own layer but to use an existing one. There are a whole set of different ORM:s out there from very simple to very feature complete.
Take a look at PetaPoco for a lightweight alternative or nHibernate for a more feature complete alternative.
Validation
One common way to make sure that mandatory fields are correctly specified and got valid values are to use a validation framework. There is one built into .net called DataAnnotations. Google it and look at some examples.
This should be checked by using business rules.
I mean if you want a very re-usable business model, business objects should be re-used elsewhere in different areas, and this may mean same class "A" could be fine in state "X" in some business, but in another situation, same class "A", will be fine in state "Y".
There's a good design pattern allowing you to implement business validators called Specification:
http://en.wikipedia.org/wiki/Specification_pattern
This can be implemented in a lot of ways, but one of most compact ones is by building rules with lambda expressions.
For example:
someAInstance => someAInstance.Name != null && someAInstance.Age > 30
Another way is using existing object validation libraries, like NHibernate Validator, which can be used standalone without NHibernate and allows you to put attributes in class' properties like [NotNull], [NotNullNotEmpty], and more complex rules, and you can either use built-in ones or you can build your own ones.
Learn more by reading this article (there you'll find a list of out-of-the-box validation rules):
http://nhforge.org/wikis/validator/nhibernate-validator-1-0-0-documentation.aspx
Note that one of most important advantages of NH Validator is it can be used in any layer, not only data or business layer, and as you can use it without NHibernate, you've a light-weight, easy-to-use and multi-layered object validator.

Categories