net

.NET Interface does not allow static/const/readonly fields

In Java, it is perfectly fine to declare an interface with static-final properties as follows:

public interface QuestionFactory
{
public static final int QTYPE_INPUT = 1;
public static final int QTYPE_RADIO = 2;
public static final int QTYPE_CHECKS = 3;

public Question createQuestion(int questionType);
}

This cannot be translated in to .NET as. The following won't work:

public interface IQuestionFactory
{
// won't work in .NET (Err: Interfaces cannot contain fields)
public static readonly int QTYPE_INPUT = 1;
public static readonly int QTYPE_RADIO = 2;
public static readonly int QTYPE_CHECKS = 3;

public Question CreateQuestion(int questionType);
}

The general recommendations in such a scenario is to externalize the const(s) in another class.

public class QuestionType

{
public const int QTYPE_INPUT = 1;

public const int QTYPE_RADIO = 2;

public const int QTYPE_CHECKS = 3;
// disclaimer: I used "const" 'cause I wanted to use it in switch/case.
// However, I assume "static readonly" could have been used as well.
}
Why is this so? The notion seems to be that interfaces cannot have states (they are stateless) and hence do not allow fields. Coming from Java world, I am not entirely sold on this argument though. I prefer one interface with all static readonly/final fields as well method-contracts (that consume those fields).

One may argue use of enum instead of int(s)... but that is a different discussion.

Topics:

Comments: 3 so far

  1. Time to consider PHP… ;-)

    Comment by Eran Galperin, Monday, May 26, 2008 @ 3:00 pm

  2. Enums is the correct answer. It’s not even a discussion…

    Comment by Hans, Monday, September 1, 2008 @ 8:20 pm

  3. “Enums is the correct answer. It’s not even a discussion…”

    An example of the WORST kind of programmer, period. It is always a discussion, or should be. I belive I am trying to fix an app written by this guys brethren.

    I see where enums could handle int consts, but that is such a limited view of the greater discussion, that I feel bad because it seems pretty obvious that the commenter doesn’t even really get the issue at hand.

    This does not mitigate the fact that any programmer who believes any problem, or proposed solution, is beyond reproach and discussion should really be sat down and talked to. As software engineers, our signle most important responsiblity is to ask and examine. And re-ask and re-examine. And then, do it again. To simply take one answer and dismiss all others outright is beyond bad practice. It warrants one investigating a new career.

    Comment by J. Code, Friday, September 5, 2008 @ 9:35 am

Leave a comment

Powered by WP Hashcash

Who is Pathfinder?

Topics

Search

WordPress

Comments about this site: info@pathf.com