I'm trying to create a class that initializes it either by passing a reference to the record in the database (with the intention that the query is launched against the database, and the return values for the properties of objects be set in it) or by specifying the values "manually" - it does not require a database call.
I reviewed a couple of tutorials to discover Best Practices for this functionality, and unfortunately I came to my senses.
I have written several examples of console applications that reflect what I consider to be the two most likely solutions, but I don’t have an idea that works best for the right work?
Sample Application # 1 uses what most books say, this is the “preferred” way, but most of the examples shown next to these statements do not really fit the context of my situation. I am worried that the thread is not as readable as application number 2.
using System;
namespace TestApp
{
public class Program
{
public static void Main(string[] args)
{
var one = new OverloadedClassTester();
var two = new OverloadedClassTester(42);
var three = new OverloadedClassTester(69, "Mike", 24);
Console.WriteLine("{0}{1}{2}", one, two, three);
Console.ReadKey();
}
}
public class OverloadedClassTester
{
public int ID { get; set; }
public string Name { get; set; }
public int age { get; set; }
public OverloadedClassTester() : this(0) { }
public OverloadedClassTester (int _ID) : this (_ID, "", 0)
{
this.age = 14;
this.Name = "Steve";
}
public OverloadedClassTester(int _ID, string _Name, int _age)
{
this.ID = _ID;
this.Name = _Name;
this.age = _age;
}
public override string ToString()
{
return String.Format("ID: {0}\nName: {1}\nAge: {2}\n\n", this.ID, this.Name, this.age);
}
}
}
This example (appendix 2) is “displayed” more readable, as I find it easier to see the workflow. However, it is really effective in terms of stored characters: p. In addition, is it not dangerous that he calls the method of the object before it is fully initialized, or is this not a problem?
using System;
namespace TestApp
{
public class Program
{
public static void Main(string[] args)
{
var one = new OverloadedClassTester();
var two = new OverloadedClassTester(42);
var three = new OverloadedClassTester(69, "Mike", 24);
Console.WriteLine("{0}{1}{2}", one, two, three);
Console.ReadKey();
}
}
public class OverloadedClassTester
{
public int ID { get; set; }
public string Name { get; set; }
public int age { get; set; }
public OverloadedClassTester()
{
initialise(0, "", 21);
}
public OverloadedClassTester (int _ID)
{
var age = 14;
var Name = "Steve";
initialise(_ID, Name, age);
}
public OverloadedClassTester(int _ID, string _Name, int _age)
{
initialise(_ID, _Name, _age);
}
public void initialise(int _ID, string _Name, int _age)
{
this.ID = _ID;
this.Name = _Name;
this.age = _age;
}
public override string ToString()
{
return String.Format("ID: {0}\nName: {1}\nAge: {2}\n\n", this.ID, this.Name, this.age);
}
}
}
What is the “right” way to solve this problem and why?
Thanks,