In C# is the ability to inspect and interact with types, objects, and members dynamically at runtime; it is useful for scenarios like code analysis, serialization, and creating extensible frameworks.
-
When
GetGetMethod().IsVirtual
is used, it typically serves to determine whether a property is an overridden property in a derived class or an original property in the base class. -
BindingFlags.Instance: This value can be passed to the
GetMembers
,GetFields
,GetProperties
, andGetMethods
methods of theType
class to specify that you only want to retrieve the instance members of the type. -
It’s important to note: In
prop.GetType().IsClass
,GetType()
is a method of theSystem.Object
class. On the other hand, inprop.PropertyType.IsPrimitive
,PropertyType
is a property ofSystem.Reflection
. Finally, inprop is decimal
, theis
keyword checks whether the value ofprop
is of type decimal; however, it does not confirm the data type itself.
var properties = obj.GetType().GetProperties();
foreach (PropertyInfo prop in properties)
if (prop.PropertyType.IsClass)
console.Writeline(prop.Name);
-
In Regression
PropertyInfo[] _properties;
- When dealing with a large number of properties in a class (where a property refers to an auto-implemented getter and setter), we declare a
PropertyInfo[] _properties
array object that holds all the properties for a specific class.
- When dealing with a large number of properties in a class (where a property refers to an auto-implemented getter and setter), we declare a
-
Recursion
property.GetValue(obj, null);
- A
System.StackOverflowException
will occur if I do not useproperty.GetValue(obj, null)
because it retrieves the value from the object and terminates recursion.
- A
-
Generic Method
public void Insert<T>(T item) {}
When we use<T>
, it indicates that the method can accept only that specific type. Example:Insert<string>("Hello world");
-
IEnumerable Interface
- Once an object has been cast to the
IEnumerable
interface, it can be used to iterate over its elements using aforeach
loop or other methods that accept anIEnumerable
object.
- Once an object has been cast to the
-
Data Types
- Dynamic Type
- Skips type-checking at compile time.
- Defers type-checking until runtime.
- All syntax checks are performed, and errors are thrown at runtime.
- Var Type
- Type-checking occurs at compile time.
- Dynamic Type
-
Cascade Feature
- Normal
StringBuilder
usage:
- Normal
var sb = new StringBuilder();
sb.Append("Hello");
sb.Append("World");
- Using the cascade feature:
var sb = new StringBuilder().Append("Hello").Append("World");