user6367252
user6367252

Reputation:

Is this considered reflection?

I had a job interview today 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 would be:

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

and then

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

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

I said that there's no reflection at all.

As good as I know Java, calling SomeClass.class.getName() does not use any of the 'reflective' packages, so it doesn't use reflection at all. I thought that C# is built that way too.

Am I dumb, or he is?

Upvotes: 5

Views: 270

Answers (3)

user1917528
user1917528

Reputation: 311

I don't have 50 reputations to add comments. Please don't mind me adding it as an answer. :) We already have a few good answers about GetType().

I'd like to answer "is a good example/case of using reflection?".

I think the intended answer is "No".

The keywords here are abstract and GetType(). The point of creating abstract classes and interfaces is that the caller doesn't have to know what the exact type it is.

If we still have to know the actual type of the sub-classes, we're not using it correctly.

So I think this is not really a question about reflection. It's more like a question about OOP/inheritance.

That's just my 2 cents.

Upvotes: 0

Kuba
Kuba

Reputation: 839

First sentences from Microsoft docs:

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

Method GetType() returns object of type Type and is used (obviously) to "get the type from an existing object". Looking only at those rules we can say it is reflection.

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

Upvotes: 3

Rich
Rich

Reputation: 15455

I think that, strictly speaking, the GetType() call is reflection, yes.

See https://stackoverflow.com/a/24377353/8261

However, it is only the most trivial reflection, so I wouldn't think you were "a "Hello World" kid" for discounting it. :-)

Am I dumb, or he is?

I don't like this framing: it seems to me that neither of you are (or perhaps both of you are, for getting into an argument over trivial semantics).

Upvotes: 7

Related Questions