Do properties implicitly initialise variables? [duplicate] - c#

This question already has answers here:
Do properties always have a value when unset?
(4 answers)
Closed 4 years ago.
I found this code on a PDF tutorial:
public class Chien
{
public static int NombreDeChiens { get; set; }
private string prenom;
public Chien(string prenomDuChien)
{
prenom = prenomDuChien;
NombreDeChiens++;
}
public void Aboyer()
{
Console.WriteLine("Wouaf ! Je suis " + prenom);
}
}
There is no initialization in this code though in the constructor there is this incrementation. So how is it possible?

A property is nothing but a field wrapped with a get- and a set-method. As fields do have an initial value, properties also do.
E.g. the following code:
public int MyProperty { get; set; }
is translated to something like this by the compiler:
private int _myProperty; // the actual name of the field defers and is only known by the compiler
public int get_MyProperty() { return this._myProperty; }
public void set_MyProperty(int value) { this._myProperty = value; }
So the question boils down to "have fields a default-value"? The answer to this question is yes, they do: null for reference-types and the default-value for all structs, e.g. 0 for int, or 0f for float.

Related

How can I make a strongly typed set of string values? [duplicate]

This question already has answers here:
Associating enums with strings in C#
(38 answers)
Can enums contain strings? [duplicate]
(6 answers)
Closed 1 year ago.
I know enums can't be strings
I would like a data structure with the utility of an enum, but one which returns strings instead of integers. To be clear, I want the return type to be the enum-like type, not string. Basically, I want to be able to force a property to be usable as a string but is only allowed to be set to a value in a defined set of strings. Something like
stringenum Unit {
Pixels = "px",
Inches = "in"
}
class Settings {
public Unit Unit { get; set; }
}
var settings = new Settings() { Unit = Unit.Pixels };
...
unitLabel.Text = settings.Unit;
I've seen some solutions that just create a class with properties that return a certain string. However, I need the return type to be limited to a set, not just any string.
EDIT FOR CLARIFICATION
Consider my previous example in addition to this method:
public void WriteUnit(Unit unit)
{
Console.WriteLine(unit);
}
// Calling
WriteUnit(Unit.Pixels); // Prints "px"
WriteUnit("px"); // ARGUMENT EXCEPTION
This method will throw an ArgumentException if you pass it a string. It only accepts the type. This is specifically what I'm looking for.
As mentioned in the comments, you cannot directly map an enum to a string.
That said, there is nothing preventing you from creating a map of enum to string values, that can only be accessed via the enum. If you maintain the mapping, you can guarantee that the value always exist.
public enum Unit
{
Pixels,
Inches
}
public static class UnitMapper
{
private static readonly Dictionary<Unit, string> _map
= new Dictionary<UserQuery.Unit, string>()
{
{ Unit.Pixels, "px" },
{ Unit.Inches, "in" }
}
public static string GetUnit(Unit unit)
{
return _map[unit];
}
}
Based on your additional comments, this can be combined with a custom user-defined implicit operator to give you the type of functionality you are looking for, although you will still have to call the overridden .ToString() to output a string.
public struct UnitWrapper
{
private readonly string _unitString;
private readonly Unit _unit;
public UnitWrapper(Unit unit)
{
_unit = unit;
_unitString = UnitMapper.GetUnit(_unit);
}
public static implicit operator UnitWrapper(Unit unit)
{
return new UnitWrapper(unit);
}
public override string ToString() => _unitString;
}
This can then be used as follows:
public class Settings
{
public UnitWrapper UnitWrapper { get; set; }
}
var settings = new Settings { UnitWrapper = Unit.Pixels };
string px = settings.UnitWrapper.ToString();

How to get value of variable from selected class In c#? [duplicate]

This question already has answers here:
How to get a property value based on the name
(8 answers)
Closed 2 years ago.
I want to get the value of a desired variable among several variables in a class
When i put string and class in Method, the method returns the value of the variable with the same name as the string received among all variables included in the class.
This method can get any type of class. So this method need to use generic.
Do anyone have a good idea for my problem?
public class A
{
public int valA_int;
public string valA_string;
public float valA_float;
public long valA_long;
}
public class B
{
public int valB_int;
public string valB_string;
public float valB_float;
public long valB_long;
}
public static class Method {
public static object GetvalueFromClass<T>(string varName, T classType) {
//Find val from class
return object;
}
}
public class Program {
public A aClass;
public B bClass;
public void MainProgram() {
object valA_int = Method.GetvalueFromClass("valA_int", aClass);
object valB_long = Method.GetvalueFromClass("valB_long", bClass);
}
}
The concept of method is like this.
please help me to figure out my problem.
your task already defined.
if you use
#{Class}.GetType().GetProperty(#{VariableName}).GetValue(#{DefinedClass}, null);
you can easily get variable from your class with variable name.
it returns variable as object. so you need to convert it
Example code
CLASS YourClass = [A CLASS WHICH IS PRE DEFINED];
object Target = YourClass.GetType().GetProperty("YOUR VARIABLE").GetValue(YourClass , null);
ok, use reflection to get all the variables in the object, then run through a loop checking them against the string of the property name. From there you should be able to return the value.
So something like
public object FindValByName(string PropName)
{
PropName = PropName.ToLower();
var props = this.GetType().GetProperties();
foreach(var item in props) {
if(item.Name.ToLower() == PropName) {
return item.GetValue(this);
}
}
}

Why and when should I use "this" to access methods from base class during inheritance in c#? [duplicate]

This question already has answers here:
When do you use the "this" keyword? [closed]
(31 answers)
Closed 3 years ago.
Noobie here, but I was wondering why and when would I need to use "this" keyword to access the Promote method in GoldenCustomer when I can already access it since GoldenCustomer is derived from the base class Customer which already has this method? Saw "this" being used in an online course but could't help but wonder.
Edit:
No my question isnt a duplicate because the other question doesnt answer when and if it is necessary to use "this" during inheritance.
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.Promote();
GoldCustomer goldCustomer = new GoldCustomer();
goldCustomer.OfferVoucher();
}
}
public class GoldCustomer : Customer{
public void OfferVoucher(){
this.Promote(); //why is this used here?
}
}
public class Customer{
public int Id { get; set; }
public string Name { get; set; }
public void Promote(){
int rating = CalculateRating(excludeOrders: true);
if (rating == 0)
System.Console.WriteLine("Promoted to level 1");
else
System.Console.WriteLine("Promoted to level 2");
}
private int CalculateRating(bool excludeOrders){
return 0;
}
}
The most common uses is when a variable in a method/function has the same name as another class-level variable.
In this case, using the this keyword will tell the compiler that you're referring to the class's variable.
For example:
public class Customer
{
public string Name { get; set; }
Public Customer (string Name, string Id)
{
this.Name = Name; // "this.Name" is class's Name while "Name" is the function's parameter.
}
}
MSDN Doc for other uses and further reading
Also, a small side-note: ID should always be stored as a string since int has the maximum value of 2147483648, and ID's are treated as a string anyway (you never use math-related functions on it like Id++ or Id = Id * 2 for example).
I'm obviously referring to state-issued IDs like "6480255197" and not "1", "2" and so on.

Property with one of (setter or getter) with body [duplicate]

This question already has answers here:
C# automatic properties - is it possible to have custom getter with default setter?
(5 answers)
Closed 3 years ago.
This question is just out of curiosity. I have a property as below
public static int MyProperty {get;set;}
which compiles successfully, but when I do
public static int MyProperty {
get
{
return 5;
}
set;
}
OR
public static int MyProperty {
get;
set
{
value = 10;
}
}
Then I get errors
'ClassName.MyProperty.set' must declare a body because it is not
marked abstract, extern, or partial
And
'ClassName.MyProperty.get' must declare a body because it is not
marked abstract, extern, or partial
respectively.
My question is why it is fine not to provide body to both getter and setter but body for either with give an error?
Because when you use this: { get; set; } is called an auto-property and it just a shortcut for having a backing field. Is the same as this:
{
get { return _field; }
set { _field = value; }
}
But this can't work with only one of both parts.
Any property should define logic for its getters and setters, if there are.
Empty getter or empty setter doesn't make any sense.
However, when you define a property like this:
public static int MyProperty { get; set; }
you tell C# to automatically generate backing field and use for simple equivalent implementation:
// This is actually what it means:
private static int _myProperty; // name for simplicity
public static int MyProperty
{
get { return _myProperty; }
set { _myProperty = value; }
}
or if expand it further:
// This is actually what it means:
private static int _myProperty; // name for simplicity
public static int get_MyProperty()
{
return _myProperty;
}
public static void set_MyProperty(int value)
{
_myProperty = value;
}
When you define a property with one auto-getter and coded setter, it doesn't really make much sense. What do you expect the property's get to do in this code?
public static int MyProperty {
get;
set
{
value = 10;
}
}

Accessing property through string name [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to set object property through Reflection
If I have the following program:
public class MyClass
{
public int MyIntProp {
get;
set;
}
public string MyStringProp {
get;
set;
}
}
public class MyMainClass
{
private const string PropertyName = "MyIntProp";
private MyClass _myClass;
public MyMainClass()
{
_myClass = new MyClass();
// _myClass.PropertyName = 5;
}
}
What I want to do is be able to assign a value of 5 to the MyIntProp property. Is it possible to do this using a string name? I though I saw something like this done before using LINQ, but I can't seem to remember the syntax or where I found it.
You can use Reflection with GetProperty method:
typeof(MyClass).GetProperty(PropertyName).SetValue(_myClass, 5);

Categories