Is this a reflection?

Today I had an interview, and I was asked if the code below is a good example / case of using reflection in C# :

 public abstract class Level{ public string LevelID { get; private set;} public int LevelNumber { get{ return int.Parse(LevelID.Substring(5).ToString()); } } public Level(){ this.LevelID = GetType().ToString(); } } 

I assume the use of the code above:

 class Level32 : Level{ // call base class constructor... } 

and then

 Level32 level = new Level32(); int id = level.LevelNumber; // would print 32. 

I think this guy meant this line: this.LevelID = GetType().ToString();

I said that there is no reflection at all.

As far as I know Java , calling SomeClass.class.getName() does not use any of the "reflective" packages, so it does not use reflection at all. I thought C# was built too.

Am I stupid or is he?

+5
source share
3 answers

I think, strictly speaking, calling GetType() is a reflection, yes.

See fooobar.com/questions/1196402 / ...

However, this is just the most trivial reflection, so I would not have thought that you are a โ€œfriendlyโ€ child โ€œHello to discount it. :-)

Am I stupid or is he?

I donโ€™t like this frame: it seems to me that neither of you (or, perhaps, both of you, got into an argument on trivial semantics).

+7
source

First suggestions from Microsoft docs:

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically instantiate a type, bind it to an existing object, or get a type from an existing object

The GetType() method returns an object of type Type and is used (obviously) to "get the type from an existing object." Looking only at these rules, we can say that this is a reflection.

To be clear, I find this a bad question for an interview, there are better ways to check if a candidate understands reflection.

+3
source

I do not have 50 reputations for adding comments. Please don't mind if I add this as an answer. :) We already have some good answers about GetType () .

I would like to answer "a good example / use case of reflection?".

I think the intended answer is "No."

Keywords: abstract and GetType () . The point of creating abstract classes and interfaces is that the caller does not need to know what the exact type is .

If we still need to know the actual type of subclasses , we do not use it correctly.

So, I think this is not a question of reflection. This is more like a question about OOP / inheritance .

This is just my 2 cents.

0
source

Source: https://habr.com/ru/post/1272368/


All Articles