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().IsVirtualis 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, andGetMethodsmethods of theTypeclass 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.Objectclass. On the other hand, inprop.PropertyType.IsPrimitive,PropertyTypeis a property ofSystem.Reflection. Finally, inprop is decimal, theiskeyword checks whether the value ofpropis 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[] _propertiesarray 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.StackOverflowExceptionwill 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
IEnumerableinterface, it can be used to iterate over its elements using aforeachloop or other methods that accept anIEnumerableobject.
- 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
StringBuilderusage:
- Normal
var sb = new StringBuilder();
sb.Append("Hello");
sb.Append("World");- Using the cascade feature:
var sb = new StringBuilder().Append("Hello").Append("World");