3

In Java I would write something like

public interface ICar {    
    static String RED_CAR = "/res/vehicles/car_red.png";
    static String BLUE_CAR = "/res/vehicles/car_blue.png";
    static String GREEN_CAR = "/res/vehicles/car_green.png";    
}

Because C# doesn't allow using fields in interface, where do I define this constants in C#, when I wish to use them more than once?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Kapparino
  • 988
  • 11
  • 33
  • 4
    What about a simple `public static class` ? and use `const` for constants, *which are implicitly static as well* – Habib Dec 19 '14 at 15:02
  • 4
    One more thing to add, these looks like path to images. Depending on the application you can use [Local Resources](http://msdn.microsoft.com/en-us/library/y99d1cd3%28v=vs.110%29.aspx) as well – Habib Dec 19 '14 at 15:04
  • Thanks, that's reasonable! – Kapparino Dec 19 '14 at 15:04

2 Answers2

11

You can define a static class to contain your constants (which need to be public as by default fields without modifier are private):

public static class Car
{
    public const string RED_CAR = "/res/vehicles/car_red.png";
    public const string BLUE_CAR = "/res/vehicles/car_blue.png";
    public const string GREEN_CAR = "/res/vehicles/car_green.png"; 
}

After this you can use constants like Car.RED_CAR.

Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50
  • 1
    @StuartLC that's true :) – Vsevolod Goloviznin Dec 19 '14 at 15:03
  • 2
    I won't use `_` in names and no BLOCK letters. Remember this is C# not C++ and also probably rename the class to `CarLocation` or something similar. – Sriram Sakthivel Dec 19 '14 at 15:06
  • 1
    @SriramSakthivel agree with you, but that's up to OP, I've just written the code based on the code he provided :) – Vsevolod Goloviznin Dec 19 '14 at 15:08
  • 1
    Public constants with a content like this (that is likely to change) isn't a very good idea because once they are changed - you need to rebuild all assemblies potentially using these. Check out [this thread](http://stackoverflow.com/questions/755685/c-static-readonly-vs-const) of an extended discussion. – Andrei Dec 19 '14 at 15:12
0

If all your constants are files it's better to include them in your resources.

In your project properties there's a resource section, vs can create a Resources.resx if you need one. In there you can add all sorts of files or strings (for translations mostly).

You can then access them through Properties.Resources.RED_CAR

I would not name them like that though. It's from the time when all variables where globals and naming conventions like that where needed to know what was stored in the variable. But when accessing your data like this it's always clear what's going on.

MrFox
  • 4,852
  • 7
  • 45
  • 81
  • Yeah, in this case I will use constants for files. Thanks for information about Properties.Resources, I didn't know about that, and I will try it right now! – Kapparino Dec 19 '14 at 15:15