Hello I need to know how to check if the object of the same type in C#.
Scenario:
class Base_Data{} class Person : Base_Data { } class Phone : Base_data { } class AnotherClass { public void CheckObject(Base_Data data) { if (data.Equals(Person.GetType())) { //<-- Visual Studio 2010 gives me error, says that I am using 'Person' is a type and not a variable. } } }
If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal.
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .
Object type checking in C# plays a pivotal role in determining the type and details of the object related to the implementation. These details are very important for programmers in terms of implementation and requirement fulfillment.
You could use the is
operator:
if (data is Person) { // `data` is an instance of Person }
Another possibility is to use the as
operator:
var person = data as Person; if (person != null) { // safely use `person` here }
Or, starting with C# 7, use a pattern-matching form of the is
operator that combines the above two:
if (data is Person person) { // `data` is an instance of Person, // and you can use it as such through `person`. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With