Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I have "public static const string S = "stuff"; in my Class?

Tags:

c#

constants

When trying to compile my class I get an error:

The constant 'NamespaceName.ClassName.CONST_NAME' cannot be marked static.

at the line:

public static const string CONST_NAME = "blah"; 

I could do this all of the time in Java. What am I doing wrong? And why doesn't it let me do this?

like image 867
jjnguy Avatar asked Jan 02 '09 22:01

jjnguy


People also ask

Can const and static used together?

So combining static and const, we can say that when a variable is initialized using static const, it will retain its value till the execution of the program and also, it will not accept any change in its value.

Can we use static with constant in C#?

From the C# language specification (PDF page 287 - or 300th page of the PDF): Even though constants are considered static members, a constant declaration neither requires nor allows a static modifier.

What is public const string?

public const string ConnectionString = "YourConnectionString"; The value in a const variable is what's called a "compile-time" value, and is immutable (which means it does not change over the life of the program). Only primitive or "built-in" C# types (e.g. int, string, double) are allowed to be declared const .

What is public static string in C#?

In C#, static means something which cannot be instantiated. You cannot create an object of a static class and cannot access static members using an object. C# classes, variables, methods, properties, operators, events, and constructors can be defined as static using the static modifier keyword.

When to make a public static readonly field?

So if the const value in the referenced assembly changes, your assembly will still have the originally compiled-in value. If this behavior is not acceptable, then you should consider making the field a public static readonly field. public class Foo { public const int HATS = 42; public static readonly int GLOVES = 33; }

Is it possible to have a static const instead of static?

You can't have static const. Try readonly instead of const or simply drop the "static" since "const" is implied static anyway. Constants cannot be replaced in the code during compilation, not runtime, so there's no requirement for static vs instance definitions.

What is the difference between Diff and const and static variables?

2 const is similar to static we can access both varables with class name but diff is static variables can be modified and const can not. Share Improve this answer Follow

Can a constant be marked static in C #27?

The constant cannot be marked static 52 Static Constants in C# 27 What is the difference between Const and Static in C#? Related 591 Can I add extension methods to an existing static class?


1 Answers

A const object is always static.

like image 80
Joel Coehoorn Avatar answered Oct 04 '22 12:10

Joel Coehoorn