Reputation: 15577
Is there a way to reference the class (i.e. Type
) that inherits a abstract class?
class abstract Monster
{
string Weakness { get; }
string Vice { get; }
Type WhatIAm
{
get { /* somehow return the Vampire type here? */ }
}
}
class Vampire : Monster
{
string Weakness { get { return "sunlight"; }
string Vice { get { return "drinks blood"; } }
}
//somewhere else in code...
Vampire dracula = new Vampire();
Type t = dracula.WhatIAm; // t = Vampire
For those who were curious... what I'm doing: I want to know when my website was last published. .GetExecutingAssembly
worked perfectly until I took the dll out of my solution. After that, the BuildDate
was always the last build date of the utility dll, not the website's dll.
namespace Web.BaseObjects
{
public abstract class Global : HttpApplication
{
/// <summary>
/// Gets the last build date of the website
/// </summary>
/// <remarks>This is the last write time of the website</remarks>
/// <returns></returns>
public DateTime BuildDate
{
get
{
// OLD (was also static)
//return File.GetLastWriteTime(
// System.Reflection.Assembly.GetExecutingAssembly.Location);
return File.GetLastWriteTime(
System.Reflection.Assembly.GetAssembly(this.GetType()).Location);
}
}
}
}
Upvotes: 3
Views: 955
Reputation: 5719
You can also get the base class information directly from the inherited class (Vampire
) using the following snippet:
Type type = this.GetType();
Console.WriteLine("\tBase class = " + type.BaseType.FullName);
Upvotes: 0
Reputation: 3848
Looks like you're just looking to get the type, which both of the above answers provide well. From the way you asked the question, I hope Monster doesn't have any code that depends on Vampire. That sounds like it would be an example of a violation of the Dependency Inversion Principle, and lead to more brittle code.
Upvotes: 2
Reputation:
You don't need the Monster.WhatIAm property. C# has the "is" operator.
Upvotes: 0
Reputation: 754725
Use the GetType()
method. It's virtual so it will behave polymorphically.
Type WhatAmI {
get { return this.GetType(); }
}
Upvotes: 7