initialize during declaration and create shorthand getter/setter - c#

How do I initialize the member variables during declaration and create the getter/setter shorthand? Is it possible or do I have to use the constructor to assign the value?
For example I want to do something similarl to this
public class Money
{
public int dollars = 200 {get; set;}
}
or
public int dollars = 200;
dollars
{
get;
set;
}

In C# 6 and later, you can initialize auto-implemented properties similarly to fields:
public string FirstName { get; set; } = "Jane";
Source: MSDN

Either
public class Money
{
private int dollars = 200;
public int Dollars
{
get { return dollars; }
set { dollars = value; }
}
}
or
public class Money
{
public int Dollars { get; set; }
public Money()
{
Dollars = 200;
}
}

Unfortunately there is currently no way to achieve this.
You must either assign the default value when you declare the properties backing field or assign the default value from the constructor if you are using an automatic property.

public class Money
{
public int Dollars {get;set;}
public Money()
{
Dollars = 200;
}
}

Related

How to automatically create a default constructor which sets default values

Is there any way to auto generate a constructor which looks like this:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public User(int id, string name)
{
Id = 0;
Name = "";
}
}
Currently I am creating a constructor like that with the refactoring tool (CTRL + .):
public User(int id, string name)
{
Id = id;
Name = name;
}
and editing each line afterwards which is pretty cumbersome when you have 20 properties per class. Is there a better way to that?
(Maybe to define a code snippet, so that we can somehow read the class properties with reflection and define them as snippet parameters?)
If you have a class with 20 properties, why do you need a constructor with 20 parameters? Maybe have a sense, but I usually create constructors to initialize properties that are relevant, to simplify the code, not to set all properties.
For your class, you can set the default values when you define the property and all constructors will use this values as the default.
public class User
{
public int Id { get; set; } = 0;
public string Name { get; set; } = string.Empty;
// Here you can even omit the constructor
public User()
{
}
}
Another thing that maybe useful is define a constructor with X parameters and reuse this constructor in other constructors with less parameters:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public User()
: this(0, string.Empty)
{
}
public User(int id, string name)
{
Id = id;
Name = name;
}
}
You can replace this(0, string.Empty) for this(default, default) if you want use the default value of each type.
If you need object create with default value for properties. You can code like this:
public class User
{
public int Id { get; set; } = 0;
public string Name { get; set; } = "";
}
Purpose of quick action "generate constructor" make method contructor for assign value to fields or properties. Don't use it in the case of just assigning default values.
do you mean initialize properties? Initializing properties through the code reflection mechanism also requires one-by-one assignments. For private object properties, it is necessary to de-private encapsulation. The operation of initializing properties in c# is generally to initialize object properties or object initializers in the form of constructors. Thank you hope it helps you
class Program
{
static void Main(string[] args)
{
Student student = new Student()
{
age = 25,
name = "java",
sex = "female"
};
}
class Student
{
public int age { get; set; }
public string name { get; set; }
public string sex { get; set; }
public Student()
{
}
public Student(int age, string name,string sex)
{
this.age = age;
this.name = name;
this.sex = sex;
}
}
}

Create object - product with name and price - best practice C#

The program should create a car which can have many parts and be able to set a part which always has a corresponding price to it.
My current car and part classes:
public class Car
{
public Car(string brand, string windshieldType, List<AdditionalCarParts> additionalCarParts) {
Brand = brand;
WindshieldType = windshieldType;
AdditionalCarParts = additionalCarParts;
}
public string Brand { get; set; }
public string WindshieldType { get; set; }
public int Price { get; set; }
public List<AdditionalCarParts> AdditionalCarParts { get; set; }
}
public class AdditionalCarParts
{
public AdditionalCarParts(PartData.PartNames part, int price) {
Part = part;
Price = price;
}
public PartData.PartNames Part { get; set; }
public int Price { get; set; }
}
public class PartData
{
public enum PartNames
{
EngineHeater,
SteeringWheelHeater,
HeadsUpDisplay,
Turbo
}
public static int EngineHeaterPrice() => 3000;
public static int SteeringWheelHeaterPrice() => 800;
public static int HeadsUpDisplayPrice() => 1200;
public static int TurboPrice() => 5000;
}
}
How to add one part to list of parts in my car, and that part has a price on it, for example:
var part = new AdditionalCarParts(PartData.PartNames.Turbo) and an object is created with price of 5000 set on it.
Should there even be a list of parts, or are there any better practices for this?
Thanks.
I would not use a class to hold the prices. I would use a data structure as a Dictionary to hold that info.
public class AdditionalCarParts
{
public AdditionalCarParts(PartData.PartNames part, int price) {
Part = part;
//Price = price;
}
public enum PartNames
{
EngineHeater,
SteeringWheelHeater,
HeadsUpDisplay,
Turbo
}
private Dictionary<PartNames, int> prices = new Dictionary<PartNames, int>() {
{ PartNames.EngineHeater, 3000 },
{ PartNames.SteeringWheelHeater, 800 },
{ PartNames.HeadsUpDisplay, 1200 },
{ PartNames.Turbo, 5000 },
};
public PartNames Part { get; set; }
public int Price(PartNames name) => prices[name];
}
"How to add one part to list of parts in my car" -> I find that adding it to the list is fine. As the prices are already pre-defined you would not need to provide the price in the class constructor.
If prices can change, you can handle that with a SetPrice method to update the dictionary. I would do:
public void SetPrice(PartNames name, int price) {
prices[name] = price;
}

Raise exception if values aren't set on initialisation

I have designed a lot of models like this:
public class Book
{
public string Title { get; set; }
public int PageCount { get; set; }
public bool SecondHand { get; set; }
}
This kind of "incomplete" initialisation doesn't raise any compiler exceptions:
new Book
{
Title = "Welcome to the The"
}
But I would like it to error at compile time, because a few non-nullable fields (int not int?) are not initialised.
How can I design models so that, upon instantiation, failing to initialise their non-nullable fields throws errors at compile time?
(And prevents compilation)
I like using the new Book { ... } instantiation syntax, instead of a constructor new Book(...), because I can see all the field names laid out before me, very visibly.
If possible, I would like a solution that can preserve this.
You can require that the mandatory properties are set via a constructor. For example, if PageCount is mandatory:
public class Book
{
public Book(int pageCount)
{
this.PageCount = pageCount;
}
public string Title { get; set; }
public int PageCount { get; }
public bool SecondHand { get; set; }
}
Now you won't be able to instanciate an instance of Book without correctly initializing it.
Now you can say:
new Book(10)
{
Title = "Welcome to the The"
}
If you want to be more explicit then you can use named parameters:
new Book(pageCount : 10)
{
Title = "Welcome to the The"
}
In the example above, if you want to make PageCount modifiable after it has been initialized in the constructor then you can give it a public setter, but still require initialization via the constructor.
The only way to avoid this is disallowing the syntax altogher. This is feasable by simply avoiding the default constructor:
public class Book
{
public Book(string title, int PageCount, bool secondHand) { ... }
public string Title { get; set; }
public int PageCount { get; set; }
public bool SecondHand { get; set; }
}

Can I set a property in a c# class to always have a specific default value?

I have a C# class with properties in which I end up using this class a a collection of type List in another class.
What I want to do is just always set the Type property to be of value "3"
Should /Can this be done with the getter/setter or should I use the System.Component.DefaultValue .... attribute
public class ReportDefinition
{
public int Id { get; set; }
public string ReportGroupNameDef { get; set; }
public int SortOrder { get; set; }
public int ReportGroupId { get; set; }
[System.ComponentModel.DefaultValue(3)]
public int Type { get; set; }
}
I think that I would prefer not using this way [System.ComponentModel.DefaultValue(3)]
You could use a read-only property, and either return the value of a private field, or just return the value you want right in the get.
public class ReportDefinition
{
private int m_type = 3;
public int Type
{
get
{
return m_type;
}
}
}
I don't expect to get or steal away the existing selected answer but I did want to help clarify a bit of the comments that I am reading.
Yes indeed best clean way is auto-property public int Type { get; } = 3; -- Caveat is C# 6
Another C# 6 without auto-property would be an expression body
private int m_type = 3;
public int Type => m_type;
However If you are stuck with wanting to use Linqpad 4 then the selected answer is "fine"
private int m_type = 3;
public int Type
{
get
{
return m_type;
}
}

How to get difference properties of object in c#?

i have a class with some properties like this:
public class Car
{
public long No { get; set; }
public string Name { get; set; }
public int Door { get; set; }
public Color Color { get; set; }
public int MaxSpeed { get; set; }
public int Price { get; set; }
}
(this class is an example, my real class is very bigger than it.)
In my program, I need to get difference properties of this class from db(not all properties each time). For example in one case I need name and color of some cars, and in other case I need name and door and price.
I want to create one method that support all difference conditions. I know that i could create it using ‘params’ and ‘enum’, but I am research about best way to do it. Thanks
You can just query the propertie when it is called.
public int Value{
get{
int myValue = getValue();
return myValue;
}
}
Try do this way:
public object[] GetProperties(int state)
{
object[] temp;
switch(state)
{
case(0):
{
temp=new object[]{Name,Color};
}break;
case(1):
{
temp=new object[]{Name,door};
}
}
}
After that, you know , what need return your function, and it's easy parse return result!

Categories