• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Coding Still

  • Home
  • About

Using generics to override static methods

October 29, 2011 By _tasos Leave a Comment

There are cases where the design of an abstract class requires that some static properties should be changed by the child classes (using the new keyword) where as the static functions remained the same. While testing, I realized that the static functions that were declared in the abstract class used the values of the static properties from the abstract class ignoring the new statement.

public abstract class abstractClass
{
    public abstractClass() { }
    public abstractClass(int num) { ID = num; }
 
    public int ID = 1;
    public static int StaticID = 10;
    public int GetIDSquare() { return ID * ID; }
    public int GetStaticIDSquare() { return StaticID * StaticID; }
}
 
public class SimpleClass : abstractClass
{
    public static new int StaticID = 20;
    public SimpleClass(int num) : base(num) { }
}

In the above example, calling the SimpleClass.GetStaticIDSquare will return 100 and not 400. This is expected, since this is how polymorphism works in most languages. C++, C# and Java have the same behaviour, where as Delphi supports polymorphism in static methods as well.

Some people would argue that if you reached this point your design probably has a flaw and you need to change it. This is a valid argument, but in some cases a less correct approach is really convenient, especially if these classes are not a part of your core architecture but some helper classes (e.g. a Data Access Layer) that will simply make the developer’s job more easy.

In order to have our static property overridden, we will use delegates. In our scenario we will change our StaticID property to a function. This function will check for the existence of the overridden function and call that instead. In our example the StaticID property is an integer, which is not nullable (something required to invoke the static method). For this reason we will change its type to string and then will simply add a wrapper method that will make the appropriate conversion. The child class will have to set the string property and not the integer property.

public abstract class abstractClass<T>
{
    public abstractClass() { }
    public abstractClass(int num) { ID = num; }
 
    public int ID = 1;
    public static int StaticID { get { return Convert.ToInt32(StaticIDStr()); } }
    public static string StaticIDStr() { return invokeStaticMethod("StaticIDStr", null) as string; }
    public int GetIDSquare() { return ID * ID; }
    public int GetStaticIDSquare() { return StaticID * StaticID; }
 
    private static Object invokeStaticMethod(String MethodName, Object[] Args)
    {
        return typeof(T).InvokeMember(MethodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, Args);
    }
}
 
public class FixedSimpleClass : abstractClass<FixedSimpleClass>
{
    public static new string StaticIDStr() { return "20"; }
    public FixedSimpleClass(int num) : base(num) { }
}

It is not the prettiest solution, but it works and that’s what is important. You can check also these two articles that helped me to come up with this solution. The second link has a few lines that explains why static methods cannot (and should not) be overridden.

  • Accessing Static Methods on a Generic class in c#
  • How to: override static methods

Filed Under: .NET Development Tagged With: OOP

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Categories

  • .NET Development
  • ASP.NET
  • Databases
  • Fun
  • IIS
  • JavaScript
  • Web Development

Tags

.NET Core Android ANTLR ASP.NET Ajax ASP.NET Core ASP.NET MVC ASP.NET Web Forms AWS Bouncy Castle Chartjs cli Client info detection Comic Continuous integration CSS Data backup Date handling Firebase Firefox addons Github HigLabo HTML5 Image manipulation jQuery JWT MySQL Nodejs Nuget OAuth Objectionjs OOP openssl Oracle ORM PHP Regular expressions SEO Social media SQL SQL Server UI/UX Url rewriting Videos Visual Studio Web design

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Secondary Sidebar

Archives

  • July 2020
  • March 2020
  • August 2019
  • December 2018
  • November 2018
  • February 2018
  • August 2016
  • June 2016
  • May 2016
  • February 2016
  • January 2016
  • August 2015
  • July 2015
  • October 2014
  • July 2014
  • November 2013
  • April 2013
  • February 2013
  • January 2013
  • December 2012
  • November 2012
  • August 2012
  • May 2012
  • February 2012
  • December 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010

Footer

Recent Posts

  • Anatomy of an Objection.js model
  • Check your RSA private and public keys
  • Round functions on the Nth digit
  • Send FCM Notifications in C#
  • Jwt Manager
  • Things around the web #5
  • Query JSON data as relational in MySQL
  • Create and sign JWT token with RS256 using the private key
  • Drop all database objects in Oracle
  • Create and deploy a Nuget package

Latest tweets

  • Geekiness Intensifies.. NASA used Three.js to render a real-time simulation of this week's NASA rover landing on M… https://t.co/orgkXnYj9O February 19, 2021 18:12
  • Things I Wished More Developers Knew About Databases https://t.co/h4gfq6NJgo #softwaredevelopment #databases May 3, 2020 12:52
  • How a Few Lines of Code Broke Lots of Packages https://t.co/p7ZSiLY5ca #javascript May 3, 2020 12:48
  • Can someone steal my IP address and use it as their own? https://t.co/HoQ7Z3BG69 January 24, 2020 13:27
  • Organizational complexity is the best predictor of bugs in a software module https://t.co/aUYn9hD4oa #softwaredevelopment January 13, 2020 08:24
  • http://twitter.com/codingstill

Misc Links

  • George Liatsos Blog
  • Plethora Themes
  • C# / VB Converter
  • Higlabo: .NET library for mail, DropBox, Twitter & more

Connect with me

  • GitHub
  • LinkedIn
  • RSS
  • Twitter
  • Stack Overflow

Copyright © 2021 · eleven40 Pro on Genesis Framework · WordPress · Log in