Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if the object is of same type

Tags:

c#

object

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.          }     } } 
like image 944
slao Avatar asked Nov 26 '10 17:11

slao


People also ask

How do you check if two objects are of the same type in Java?

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.

How do you check if an object is of a certain type Java?

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 .

Is object check in C#?

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.


1 Answers

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`. } 
like image 195
Darin Dimitrov Avatar answered Oct 09 '22 02:10

Darin Dimitrov