Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-inferring a constant in C#

In C#, the following type-inference works:

var s = "abcd"; 

But why can't the type be inferred when the variable is a constant?

The following throws a compile-time exception:

const var s = "abcd"; // <= Compile time error:                        //    Implicitly-typed local variables cannot be constant 
like image 854
Andreas Grech Avatar asked Jan 24 '10 19:01

Andreas Grech


People also ask

Does C use type inferencing?

Type inference is a feature that is common to a variety of programming languages. While, in the past, it has been prominently present in functional ones (e.g., ML and Haskell), today, many object-oriented/ multi-paradigm languages such as C# and C++ offer, to a certain extent, such a feature.

What is inference in C?

Master C and Embedded C Programming- Learn as you go Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages.

What is inferred datatype?

Type inference is the ability to automatically deduce, either partially or fully, the type of an expression at compile time. The compiler is often able to infer the type of a variable or the type signature of a function, without explicit type annotations having been given.

What is type inference in Python?

Type inference for dynamic programming languages such as Python is an important yet challenging task. Static type inference tech- niques can precisely infer variables with enough static constraints but are unable to handle variables with dynamic features.


1 Answers

I'm actually hoping Lippert pops by and and takes a look at the question

If there's something you want brought to my attention, you can leave my name in the text -- not a comment -- and I'll find it eventually. Or, better, you can "tweet" to @ericlippert. Note that this does not constitute a service level agreement; I do this in my spare time.

why can't the type be inferred when the variable is a constant?

"constant" and "variable" are opposites. const var gives me the shudders to type. A constant is a value that never changes and has no storage location; a variable is a storage location whose contents change. They're completely different, so don't attempt to combine them. The var syntax was chosen to call out "this is a variable", and we're sticking with it.

var can stand in for a specific type declaration, but combining it with const severely muddies the picture of what the compiler does with the value. Therefore const var is disallowed to prevent this confusion and you have to explicitly type your constants.

I would be perfectly fine with inferred constants that do not use var:

const Pi = 3.14159; 

seems fine to me. However, I know of no plans to add this to C#.

like image 116
Eric Lippert Avatar answered Sep 24 '22 18:09

Eric Lippert