Is this the best option for converting a java interface with static fields in an abstract class in C #?

public interface IHashStorage<T> { public static final float INITIAL_LOAD_FACTOR = 0.7f; public static final int INITIAL_CAPACITY = 149; } 

I have the code above that needs to be translated into C #. The only solution that seems right is to make it an abstract class. From what I found safer, use readonly than const:

 public abstract class IHashStorage<T> { private readonly float INITIAL_LOAD_FACTOR = (float)0.7; private readonly int INITIAL_CAPACITY = 149; } 

A project in Java uses the Decorator and Proxy templates; to convert from java to C # you may need to use more abstract classes (currently only interfaces are used in java)? I know theoretically the difference between the two, but practically in C # I used abstract classes more. I am not familiar with java, and I would like to know your advice on how to find the best solution to solve this problem. I mean the main points to consider when converting code.

+5
source share
2 answers

I would define an interface with the get property.
then, so that my base class implements it and sets the default values
and then extend the base class for each java class that implements the java interface.
something like that:

 public interface IHashStorage<T> { float InitialLoadFactor { get; } int InitialCapacity { get; } } public class HashStorageBase<T> : IHashStorage<T> { private readonly float _initialLoadFactor = 0.7f; private readonly int _initialCapacity = 149; public float InitialLoadFactor { get { return _initialLoadFactor; } } public int InitialCapacity { get { return _initialCapacity; } } } public class HashStorage1<T> : HashStorageBase<T> { ... } 
+1
source

As I mean in my comment, there is no way to bind fields (or any other implementation details) to a C # interface. You have two options, except that it is an abstract class:

  • Enter fields in (possibly read-only) properties on the interface that will force all implementations to specify them.
  • Make fields into user attributes defined on the interface and / or in implementations.
+1
source

All Articles