This question already has answers here:
get name of a variable or parameter [duplicate]
(3 answers)
Closed 6 years ago.
How to get variable name of this?
var thename = new myclass();
Whereas I want the variable name "thename" inside myclass instance?
What do you expect in the following scenario?
var theName = new MyClass();
var otherName = theName;
someList.Add(otherName);
The name(s) you're after don't belong to the instance but to the variables referencing it.
There are now three references pointing to the same instance. Two have distinct names, the third does not really have a name.
Inside a MyClass object, you can't know who's pointing at you. Heap objects themselves are always anonymous.
public class myclass()
{
public string VariableName { get; set; }
}
var theName = new myclass();
theName.VariableName = nameof(theName);
Instantiating the variable like this, it doesn't exist to have a name before you create the object. If you want to force every instance to populate that variable, then you can do something like this, but your code will be a little more verbose:
public class myclass()
{
public myclass(string variableName)
{
if (string.IsNullOrWhitespace(variableName)
{
throw new ArgumentNullException(nameof(variableName);
}
VariableName = variableName;
}
public string VariableName { get; private set; }
}
myclass theName;
theName = new myclass(nameof(myclass));
Of course, there's no guarantee that someone isn't passing in a different string.
Related
This question already has answers here:
What is difference between Init-Only and ReadOnly in C# 9?
(4 answers)
Closed 1 year ago.
I can define a class like below:
public class MyClass
{
public int Id { get; }
public MyClass(int id) => Id = id;
}
And I have to define the Id from the constructor and it will be read-only.
But if I want to use Init only setters in the C# 9.0, what does it and how can I use it?
public class MyClass
{
public int Id { get; init; }
}
Init only setters provide consistent syntax to initialize members of an object. Property initializers make it clear which value is setting which property. The downside is that those properties must be settable.
With that, you don't need to provide the value at the beginning and the constructor and you can do it afterward:
var myClass = new MyClass
{
Id = 10
}
and it will be sealed and you cannot change it anymore.
myClass.Id = 43; // not allowed
read more info
In a nutshell:
var obj = new MyClass
{
Id = 42 // totally fine
};
obj.Id = 43; // not OK, we're not initializing
Trivial in this case and not much different to using a constructor parameter, but useful in some more complex scenarios where you don't want 200 constructor parameters, but you do want it to be outwardly immutable once constructed.
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.
This question already has answers here:
Comparing Object properties using reflection
(5 answers)
Closed 3 years ago.
I would like to know if there is a way to create a custom class out of an existing class in this manner:
original class:
public class Person
{
string name;
}
later in code:
var diffPerson = CreateDiffClass<Person>();
diffPerson.name.Value = "name";
diffPerson.name.Changed = false;
this diffPerson is not of Person type, instead it is custom created one, that for every variable in Person have one in itself so that the new variable is a tuple where T is the type of the variable.
I want it to create a system for comparing 2 instances of the same class. one old instance and one new and save the new value and if it changed
I don't really know how to describe it except showing in this example so I hope it is understandable..
I want this to be generic and work on any given class
Thanks
You can declare a generic class like this
public class CustomValue<T>
{
public T Value { get; set; }
public bool Changed { get; set; }
}
and then use it like this
public class Person
{
public CustomValue<string> Name;
}
later in code
var diffPerson = new Person();
diffPerson.Name = new CustomValue<string>();
diffPerson.Name.Value = "name";
diffPerson.Name.Changed = false;
I learned about following syntax today
protected String TaskTitle { get; set; }
If I am correct this essentially translates to something like:
String _taskTitle;
protected String TaskTitle {
get { return _taskTitlel }
set { _taskTitle = value; }
}
My question is how can we use it now with objects to set and get certain values? Lets assume object is named MyTest(String title) how would I set TaskTitle equal to a passed in argument title? and afterwards instead of having methods like .getTitle(..) .setTitle(..) how would I take advantage of this {get; set;} syntax?
I understand that this might be getting long, but I believe this "sub question" belongs here, can I use this for arrays? Lets assume I have other object named MyTestTwo(String title, String description, int number); That inherits from first one, and I'd like to have an array MyTestTwo[] { get; set; } as part of MyTest() object, how could I populate it?
I know this might be a lot to ask, but I want to understand this {get; set;} syntax as I am new to it and new to c# in general, so far documentation is a bit confusing to me.
You should mark your property public to 'see' it in classes that do not derive your current class.
You can set it like this then:
yourInstance.TaskTitle = "test 123";
As an answer on your second question:
You can populate the array like you normally would when using variables:
yourInstance.ArrayProperty = new string[1];
yourInstance.ArrayProperty[0] = "test 123";
You can use the { get; set; } syntax like this to modify properties on existing objects:
myTest.TaskTitle = "A brand new title";
And like this to read data from existing objects
string currentTitle = mytest.TaskTitle;
Additionally you can use the following shorthand syntax to initialize a new object:
MyTest myTest = new MyTest{ TaskTitle = "a new task"};
There's some other shorthand syntax you can use for initializing ICollection data structures, which is explained quite well here: http://msdn.microsoft.com/en-us/library/bb384062.aspx
in C# you use the properties by either getting the value via a string a = class.TaskTitle; or setting via class.TaskTitle = "foo";
As far as array objects, try this:
Foo foo = new Foo();
foo.bar = new Bar[5];
foo.bar[0] = new Bar();
foo.bar[1] = new Bar();
...
After which you can access the properties of the Bar via the same syntax as any other object:
foo.bar.SomeMethod();
Or, sans nested classes:
Foo[] foo = new Foo[2];
foo[0] = new Foo();
foo[1] = new Foo();
i am assuming this is your constructor
MyTest(String title)
{
TaskTitle=title;
}
Modifier returntype PropertyName
{
get;
set;
}
get and set are methods ....in c# we use them becouse they are compact and simple.
or you can use methods get and set by creating in your class separately...like
public returntype get()
{
return yourPrivateMember;//
}
public returntype set(type value)
{
yourPrivateMember=value;//in certain cases you dont want the user the mess your private variable and you can control how the user interacts with your private variables
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I read the properties of a C# class dynamically?
I have to get values of class members using strings of their names only. I think I have to use Reflection but I am not realy sure how to. Can you help me?
MemberInfo member = typeof(MyClass).GetMember("membername");
GetMember reference.
If you know type of member you're looking for, you can use .GetMethod, .GetField, .GetProperty, etc.
If you don't know the type you are working with:
var myobject = someobject;
string membername = "somemember";
MemberInfo member = myobject.GetType().GetMember(membername);
Different member types have different means to getting the value. For a property you would do:
var myobject = someobject;
string propertyname = "somemember";
PropertyInfo property = myobject.GetType().GetProperty(membername);
object value = property.GetValue(myobject, null);
public class Foo
{
public string A { get; set; }
}
public class Example
{
public void GetPropertyValueExample()
{
Foo f = new Foo();
f.A = "Example";
var val = f.GetType().GetProperty("A").GetValue(f, null);
}
}