I am trying to port an existing c# to f# and would I am getting stuck on porting this c# line:
public object myInnerOject
In C# object is just a type name referring to System.Object. In F#, you can either use this full .NET name or a type alias obj.
Now, regarding a field declaration - there are various ways to write that depending on the context. Also, it is a good practice to initialize all fields in F#, so it would be useful to see larger context of your code.
However, you may write this:
type A() =
let mutable (myInnerObj:obj) = null
This creates a private field myInnerObj of type System.Object initialized to null, which is mutable can can be assigned later (myInnerObj <- new Random(), for example). I used example with private field, because public fields are generally discouraged in .NET.
#Tomas is right. You may also want to check out these blogs:
The basic syntax of F# - types
What does this C# code look like in F#?
Related
This question already has answers here:
Use of var keyword in C#
(86 answers)
Closed 8 years ago.
I usually create a object like these:
List<Student> students= new List<Student>();
but when I install the resharper in vs2012,it suggest me to create a object like these:
var students= new List<Student>();
I wonder whether they have the same effect.I think they have the same effect.Will it be better when I use var?
As suggested by Brad Smith http://www.brad-smith.info/blog/archives/336 :-
There seems to be a tendency for some programmers to use var for every
variable declaration. Sure, the language doesn’t stop you from doing
this and, indeed, MSDN admits that this is a “syntactic convenience”…
But it also warns quite strongly that:
the use of var does have at least the potential to make your code
more difficult to understand for other developers. For that reason,
the C# documentation generally uses var only when it is required.
Implicitly Typed Local Variables (C# Programming Guide), MSDN
I discovered recently that the commonly-used tool ReSharper
practically mandates liberal use of var. Frankly, this isn’t helping
the situation. There are some developers who try to argue the stance
that var somehow improves readability and broader coding practices,
such as this article:
By using var, you are forcing yourself to think more about how you
name methods and variables, instead of relying on the type system to
improve readability, something that is more an implementation detail…
var improves readability, Hadi Hariri
I agree with the premise of the quote above, but not with the end
result. On the contrary, the overuse and misuse of var can lead to
some very bad habits…
Let’s look at the argument against the widespread use of var (and for
its sparing, correct use):
Implicitly-typed variables lose descriptiveness
The type name provides an extra layer of description in a local
variable declaration:
// let's say we have a static method called GetContacts()
// that returns System.Data.DataTable
var individuals = GetContacts(ContactTypes.Individuals);
// how is it clear to the reader that I can do this?
return individuals.Compute("MAX(Age)", String.Empty);
My variable name above is perfectly descriptive; it differentiates
between any other variables populated using GetContacts() and indeed
other variables of type DataTable. When I operate on the variable, I
know that it’s the individual contacts that i’m referring to, and that
anything I derive from them will be of that context. However, without
specifying the type name in the declaration, I lose the
descriptiveness it provides…
// a more descriptive declaration
DataTable individuals = GetContacts(ContactTypes.Individuals)
When I come to revisit this body of code, i’ll know not only what the
variable represents conceptually, but also its representation in terms
of structure and usage; something lacking from the previous example.
No difference, by typing var instead of the data type that you are using, you just make the compiler look and set the data type himself. It makes the code a little shorter but in my opinion its better to write the data types full name instead of var.
It is same. But, the only difference is that, compiler determines the type of the variable.
How C# compiler does know the type of the variable?
The C# compiler infers the type of the variable from the
right-hand-side expression. For example, the type for the students is inferred from the type of the right-hand-side expression new List<Student>(), which makes students a type of
List<Student>().
var is just a syntactic sugar. It aliases any type. In your case, there is no difference between them. They both produce same Intermediate Language code.
Using var is just saying: "Hey compiler, just determine the type of this variable"
var just infers the type. You can use it in declarations like this when the resulting type is pretty obvious - it makes the code easier to read but doesn't make a difference to the compiler.
See also:
What is the significance of “var” keyword in c#.Net?
var (C# Reference)
Currently, I'm reading C# 5.0 in a Nutshell and in the Type Basics (located at Chapter 2) subtopic the term symmetry of predefined types and custom types is introduced...
...why the author talks about symmetry between those types? What are the argument to say that types are symmetric?
This is the original paragraph:
A beautiful aspect of C# is that predefined types and custom types have few differences. The predefined int type serves as a blueprint for integers. It holds data -32 bits- and provides function members that use that data, such as ToString. Similarly, our custom UnitConverter type acts as a blueprint for unit conversions. It holds data -the ratio- and provides function members to use that data.
The meaning of the text is that all of the types in the language "behave like objects". For example, you can do this:
int i = 42;
Console.WriteLine(i.ToString()); // called a method on an int
as easily as you can do this:
DateTime d = DateTime.Now;
Console.WriteLine(d.ToString()); // called a method on a DateTime
That is, if you did not know the types of i and d you would not be able to deduce anything by just reading the code that calls .ToString().
Contrast this with a language like C++:
std::string s = "hello";
std::cout << s.length();
int i = 42;
// ...but you cannot invoke any method on i; "ints are special"
Here the fact that s.length() compiles tells us that s is not an int, or a pointer, or any other primitive type.
This uniformity does not buy you anything from a technical standpoint, but it is nevertheless a welcome feature -- especially if you are just learning the language.
I believe the author's point is that built-in types and custom types are both meant to serve similar purposes; hold data and provide mechanisms for using that data. I believe there is also a veiled reference in there that both built-in objects and custom objects inherit from System.Object, thus they share similar abilities (i.e. ToString()).
I do not necessarily agree with term 'symmetry', but that is my two cents on the topic.
There are languages where you can't create type that behave similarly to something that is built in like int. In C# one can create type with all properties of 'int' (which is synonym of System.Int32) - value type with +/-/=operation.
I.e. in JavaScript one can't create another Array type or string type. In Java value types are (were?) not present, so type equivalent to 'int' can't be written by programmer ( Does Java make distinction between value type and reference type ).
I am reading the latest edition of this book for C# 10 and had the same question. I like all of the answers so far provided, but have one additional point: this is a reference to the utility of C#'s unified type system, which the author mentions briefly in Chapter 1 under the section 'Object Orientation':
Unified type system
The fundamental building block in C# is an encapsulated unit of data and functions called a type. C# has a unified type system in which all types ultimately share a common base type. This means that all types, whether they represent business objects or are primitive types such as numbers, share the same basic functionality. For example, an instance of any type can be converted to a string by calling its ToString() method.
To distill the author's writing and the comments from others down into a few points:
The type system of C# is unified, in that all types inherit from the common System.Object type.
Logically, type components can be logically grouped into two components: data members and function members.
Practically, because types behave like objects (they all have some data and/or behavior); developers can expect a minimum set of functionality from all types when using C#, such as the ability to call .ToString(), among other things.
These three points seem to be what the author had in mind when he referred to the C# type system having a 'symmetric beauty'.
In C#, the following code doesn't compile:
class Foo {
public string Foo;
}
The question is: why?
More exactly, I understand that this doesn't compile because (I quote):
member names cannot be the same as their enclosing type
Ok, fine. I understand that, I won't do it again, I promise.
But I really don't understand why the compiler refuses to take any field having the same name as an enclosing type. What is the underlying issue that prevents me to do that?
Strictly speaking, this is a limitation imposed by C#, most likely for convenience of syntax. A constructor has a method body, but its member entry in IL is denoted as ".ctor" and it has slightly different metadata than a normal method (In the Reflection classes, ConstructorInfo derives from MethodBase, not MethodInfo.) I don't believe there's a .NET limitation that prevents creating a member (or even a method) with the same name as the outer type, though I haven't tried it.
I was curious, so I confirmed it's not a .NET limitation. Create the following class in VB:
Public Class Class1
Public Sub Class1()
End Sub
End Class
In C#, you reference it as:
var class1 = new Class1();
class1.Class1();
Because Foo is reserved as the name of the constructor.
So if your code was allowed - what would you call the constructor?
Even if it was possible to do this by treating the constructor as a special case and introducing new rules into method / member binding - would it be a good idea? It would inevitably lead to confusion at some point.
Because the member name clashes with the name of the class's constructor?
There is a right way to do it and a wrong way to do it.
Why Doesn't C# allow it?
Because it does not reason to do so. Why would you want to create such confusion in your life.
I think the CLR allows it, as another post proves with a vb.net example and it should not be restricted, but I would not want to create an application based on the same rules that the CLR operates in. The abstraction makes code more clear. I think the argument works on the same level as multiple inheritance. Yes it can be done in some languages, but it causes confusion. My answer therefore would be to reduce ambiguity and confusion and is based in the c# parser/compiler. A design choice by the C# team.
I have a C# 4.0 parser. It accepts 'dynamic' as a keyword as a type. My parser trips over
statements found in working C# 3.0 programs of the form of:
dynamic = <exp> ;
So, it dynamic really a keyword? Or can it still be used as an arbitrary identifier name? (If so, why isn't 'int' treated the same way)?
Is there a reference spec somewhere that states whether dynamic is keyword? The latest ECMA C# 4 specification doesn't even mention 'dynamic', and the best I can find at the MS site is a "preliminary specification" which says its a keyword but I suspect that's just sloppy writing.
dynamic is a contextual keyword as of C# 4.0. The fourth edition of the ECMA C# spec does not refer to C# 4.0. (Note the 2006 publication date.)
MSDN describes it as a keyword.
It's also in this table of contextual keywords. (Scroll down.)
It's not a "normal" keyword like if, for etc.
It's a contextual keyword like yield, from etc.
In particular, this compiles:
object dynamic = 0; // dynamic is a contextual keyword
but this doesn't:
object string = 0; // string is a regular keyword
You'd have to "escape" string like this:
object #string = 0;
This makes a lot of sense in terms of backward compatibility: it's unlikely that many people will have created a type called dynamic (which would cause ambiguity; IIRC the "real" type wins in this case) whereas it's very likely that existing code uses variables called dynamic.
In some ways it doesn't even need to be a contextual keyword (and I don't believe the specification ever explicitly refers to it as such) - you can think of it as the name of a type which is always available (like string and object). I would imagine that string etc were made keywords from v1 to avoid confusion, but adding genuine keywords (which can't be used as identifiers) would have a high compatibility cost now.
It's a keyword. (see edit below) I'm a little confused on what you mean by "why isn't 'int' treated the same way?"
You can't do this: int int = 5;
But you can do this, although it's not good practice: int #int = 5;
The C# 4.0 spec does mention dynamic in section 20.1.
EDIT: more info...
Using dynamic as a variable name is allowed, so it's not a keyword (but it is a contextual keyword - see Sean Devlin's post). See the screenshot below using .NET 4.0 beta
Check out Chris Burrow's blog post. An interesting quote from the post:
As you can see, the publicly visible
members that use the type dynamic
actually, behind the scenes, use the
type object when they are emitted.
There is no framework type "dynamic."
However, those "objects" are all
decorated in such a way that the
compiler (or anyone else) can tell
that they are meant to be handled
dynamically.
I am a PHP web programmer who is trying to learn C#.
I would like to know why C# requires me to specify the data type when creating a variable.
Class classInstance = new Class();
Why do we need to know the data type before a class instance?
As others have said, C# is static/strongly-typed. But I take your question more to be "Why would you want C# to be static/strongly-typed like this? What advantages does this have over dynamic languages?"
With that in mind, there are lots of good reasons:
Stability Certain kinds of errors are now caught automatically by the compiler, before the code ever makes it anywhere close to production.
Readability/Maintainability You are now providing more information about how the code is supposed to work to future developers who read it. You add information that a specific variable is intended to hold a certain kind of value, and that helps programmers reason about what the purpose of that variable is.
This is probably why, for example, Microsoft's style guidelines recommended that VB6 programmers put a type prefix with variable names, but that VB.Net programmers do not.
Performance This is the weakest reason, but late-binding/duck typing can be slower. In the end, a variable refers to memory that is structured in some specific way. Without strong types, the program will have to do extra type verification or conversion behind the scenes at runtime as you use memory that is structured one way physically as if it were structured in another way logically.
I hesitate to include this point, because ultimately you often have to do those conversions in a strongly typed language as well. It's just that the strongly typed language leaves the exact timing and extent of the conversion to the programmer, and does no extra work unless it needs to be done. It also allows the programmer to force a more advantageous data type. But these really are attributes of the programmer, rather than the platform.
That would itself be a weak reason to omit the point, except that a good dynamic language will often make better choices than the programmer. This means a dynamic language can help many programmers write faster programs. Still, for good programmers, strongly-typed languages have the potential to be faster.
Better Dev Tools If your IDE knows what type a variable is expected to be, it can give you additional help about what kinds of things that variable can do. This is much harder for the IDE to do if it has to infer the type for you. And if you get more help with the minutia of an API from the IDE, then you as a developer will be able to get your head around a larger, richer API, and get there faster.
Or perhaps you were just wondering why you have to specify the class name twice for the same variable on the same line? The answer is two-fold:
Often you don't. In C# 3.0 and later you can use the var keyword instead of the type name in many cases. Variables created this way are still statically typed, but the type is now inferred for you by the compiler.
Thanks to inheritance and interfaces sometimes the type on the left-hand side doesn't match the type on the right hand side.
It's simply how the language was designed. C# is a C-style language and follows in the pattern of having types on the left.
In C# 3.0 and up you can kind of get around this in many cases with local type inference.
var variable = new SomeClass();
But at the same time you could also argue that you are still declaring a type on the LHS. Just that you want the compiler to pick it for you.
EDIT
Please read this in the context of the users original question
why do we need [class name] before a variable name?
I wanted to comment on several other answers in this thread. A lot of people are giving "C# is statically type" as an answer. While the statement is true (C# is statically typed), it is almost completely unrelated to the question. Static typing does not necessitate a type name being to the left of the variable name. Sure it can help but that is a language designer choice not a necessary feature of static typed languages.
These is easily provable by considering other statically typed languages such as F#. Types in F# appear on the right of a variable name and very often can be altogether ommitted. There are also several counter examples. PowerShell for instance is extremely dynamic and puts all of its type, if included, on the left.
One of the main reasons is that you can specify different types as long as the type on the left hand side of the assignment is a parent type of the type on the left (or an interface that is implemented on that type).
For example given the following types:
class Foo { }
class Bar : Foo { }
interface IBaz { }
class Baz : IBaz { }
C# allows you to do this:
Foo f = new Bar();
IBaz b = new Baz();
Yes, in most cases the compiler could infer the type of the variable from the assignment (like with the var keyword) but it doesn't for the reason I have shown above.
Edit: As a point of order - while C# is strongly-typed the important distinction (as far as this discussion is concerned) is that it is in fact also a statically-typed language. In other words the C# compiler does static type checking at compilation time.
C# is a statically-typed, strongly-typed language like C or C++. In these languages all variables must be declared to be of a specific type.
Ultimately because Anders Hejlsberg said so...
You need [class name] in front because there are many situations in which the first [class name] is different from the second, like:
IMyCoolInterface obj = new MyInterfaceImplementer();
MyBaseType obj2 = new MySubTypeOfBaseType();
etc. You can also use the word 'var' if you don't want to specify the type explicitely.
Why do we need to know the data type
before a class instance?
You don't! Read from right to left. You create the variable and then you store it in a type safe variable so you know what type that variable is for later use.
Consider the following snippet, it would be a nightmare to debug if you didn't receive the errors until runtime.
void FunctionCalledVeryUnfrequently()
{
ClassA a = new ClassA();
ClassB b = new ClassB();
ClassA a2 = new ClassB(); //COMPILER ERROR(thank god)
//100 lines of code
DoStuffWithA(a);
DoStuffWithA(b); //COMPILER ERROR(thank god)
DoStuffWithA(a2);
}
When you'r thinking you can replace the new Class() with a number or a string and the syntax will make much more sense. The following example might be a bit verbose but might help to understand why it's designed the way it is.
string s = "abc";
string s2 = new string(new char[]{'a', 'b', 'c'});
//Does exactly the same thing
DoStuffWithAString("abc");
DoStuffWithAString(new string(new char[]{'a', 'b', 'c'}));
//Does exactly the same thing
C#, as others have pointed out, is a strongly, statically-typed language.
By stating up front what the type you're intending to create is, you'll receive compile-time warnings when you try to assign an illegal value. By stating up front what type of parameters you accept in methods, you receive those same compile-time warnings when you accidentally pass nonsense into a method that isn't expecting it. It removes the overhead of some paranoia on your behalf.
Finally, and rather nicely, C# (and many other languages) doesn't have the same ridiculous, "convert anything to anything, even when it doesn't make sense" mentality that PHP does, which quite frankly can trip you up more times than it helps.
c# is a strongly-typed language, like c++ or java. Therefore it needs to know the type of the variable. you can fudge it a bit in c# 3.0 via the var keyword. That lets the compiler infer the type.
That's the difference between a strongly typed and weakly typed language. C# (and C, C++, Java, most more powerful languages) are strongly typed so you must declare the variable type.
When we define variables to hold data we have to specify the type of data that those variables will hold. The compiler then checks that what we are doing with the data makes sense to it, i.e. follows the rules. We can't for example store text in a number - the compiler will not allow it.
int a = "fred"; // Not allowed. Cannot implicitly convert 'string' to 'int'
The variable a is of type int, and assigning it the value "fred" which is a text string breaks the rules- the compiler is unable to do any kind of conversion of this string.
In C# 3.0, you can use the 'var' keyword - this uses static type inference to work out what the type of the variable is at compile time
var foo = new ClassName();
variable 'foo' will be of type 'ClassName' from then on.
One things that hasn't been mentioned is that C# is a CLS (Common Language Specification) compliant language. This is a set of rules that a .NET language has to adhere to in order to be interopable with other .NET languages.
So really C# is just keeping to these rules. To quote this MSDN article:
The CLS helps enhance and ensure
language interoperability by defining
a set of features that developers can
rely on to be available in a wide
variety of languages. The CLS also
establishes requirements for CLS
compliance; these help you determine
whether your managed code conforms to
the CLS and to what extent a given
tool supports the development of
managed code that uses CLS features.
If your component uses only CLS
features in the API that it exposes to
other code (including derived
classes), the component is guaranteed
to be accessible from any programming
language that supports the CLS.
Components that adhere to the CLS
rules and use only the features
included in the CLS are said to be
CLS-compliant components
Part of the CLS is the CTS the Common Type System.
If that's not enough acronyms for you then there's a tonne more in .NET such as CLI, ILasm/MSIL, CLR, BCL, FCL,
Because C# is a strongly typed language
Static typing also allows the compiler to make better optimizations, and skip certain steps. Take overloading for example, where you have multiple methods or operators with the same name differing only by their arguments. With a dynamic language, the runtime would need to grade each version in order to determine which is the best match. With a static language like this, the final code simply points directly to the appropriate overload.
Static typing also aids in code maintenance and refactoring. My favorite example being the Rename feature of many higher-end IDEs. Thanks to static typing, the IDE can find with certainty every occurrence of the identifier in your code, and leave unrelated identifiers with the same name intact.
I didn't notice if it were mentioned yet or not, but C# 4.0 introduces dynamic checking VIA the dynamic keyword. Though I'm sure you'd want to avoid it when it's not necessary.
Why C# requires me to specify the data type when creating a variable.
Why do we need to know the data type before a class instance?
I think one thing that most answers haven't referenced is the fact that C# was originally meant and designed as "managed", "safe" language among other things and a lot of those goals are arrived at via static / compile time verifiability. Knowing the variable datatype explicitly makes this problem MUCH easier to solve. Meaning that one can make several automated assessments (C# compiler, not JIT) about possible errors / undesirable behavior without ever allowing execution.
That verifiability as a side effect also gives you better readability, dev tools, stability etc. because if an automated algorithm can understand better what the code will do when it actually runs, so can you :)
Statically typed means that Compiler can perform some sort of checks at Compile time not at run time. Every variable is of particular or strong type in Static type. C# is strongly definitely strongly typed.