Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to define constants and use them anywhere?

Tags:

c#

oop

interface

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?

like image 871
Kapparino Avatar asked Jan 25 '26 17:01

Kapparino


1 Answers

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.

like image 115
Vsevolod Goloviznin Avatar answered Jan 28 '26 21:01

Vsevolod Goloviznin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!