Skip to content

Instantly share code, notes, and snippets.

@iArmanKarimi
Last active December 5, 2021 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iArmanKarimi/b94f26a33889ea83a795bcd609ed6156 to your computer and use it in GitHub Desktop.
Save iArmanKarimi/b94f26a33889ea83a795bcd609ed6156 to your computer and use it in GitHub Desktop.
setting value to the fields, properties, etc. on runtime

C# setting value to the fields, properties, etc.

It is possible to get methods, fields, properties, enums, interfaces etc. from Class.GetType(). It is also possible to change them dynamically (on runtime).

for example, when we have fields of type String and we want to set their value equal to their names:

class Base {
	public string myField;
	public string myProperty {get; set;}
}

class Derived: Base {
	public Derived {
		var fields = base.GetType().GetFields();
		foreach (var field in fields) {
			field.SetValue(this, field.Name);
		}
	}
}

Get an array of fields with type of String:

class MyClass {

	public string x = "x", apple = "Apple", name = "C#";
	
	public string[] GetArray()
	{
		var fields = GetType().GetFields();
		var arr = new List<string>(fields.Length);

		foreach (var field in fields)
			arr.Add((string)field.GetValue(this));

		return arr.ToArray();
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment