Reputation: 1668
I have a base class BaseModel, and and a subclass SubModel. I want to define a function inside BaseModel that will return the string name of the class. I have this working for instances of BaseClass, but if I make an SubModel instance, the function still returns "BaseModel". Here is the code?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ClassLibrary1
{
public class BaseModel
{
public string GetModelName()
{
return MethodBase.GetCurrentMethod().ReflectedType.Name;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClassLibrary1;
namespace ConsoleApplication1
{
class SubModel : BaseModel
{
}
}
And I would like this call:
SubModel test = new SubModel();
string name = test.GetModelName();
To return "SubModel". Is this possible?
Thanks.
Upvotes: 0
Views: 236
Reputation: 5944
You can just do this:
public class BaseModel
{
public string GetModelName()
{
return this.GetType().Name;
}
}
class SubModel : BaseModel
{
}
SubModel test = new SubModel();
string name = test.GetModelName();
This is also possible:
string name = (test as BaseModel).GetModelName();
string name = ((BaseModel)test).GetModelName();
//both return "SubModel"
Upvotes: 9