I am very new to c#, but I am learning more every day.
I am wondering what the following means:
private DataIdentifier dataIdentifier;
Why do they write like this? It is almost the same name but they use big D in the first word.
This declares a member variable (i.e. a "field") in a class.
private is the access modifier. It specifies that the variable can only be accessed from within the class. The access modifier is optional, and defaults to private (but it's considered best practice to be explicit anyway).
DataIdentifier is the type of the variable (i.e., only instances of the DataIdentifier class can be put into the variable).
dataIdentifier is the name of the variable. This is what you write in the code when you want to access the object that's being held in the variable.
Note: Technically, objects are not actually "in" a variable; the variable is typically a pointer to a location in memory where the object actually is (it "references" an object).
As you learn more C#, you'll see a common idiom where the name of the property is the same as the name of the type:
public SpaceShip SpaceShip;
This is allowed since the compiler is smart enough to know whether you're referring to the variable or the class itself when you type SpaceShip in your code, just from the context.
DataIndentifier is a type.
dataIdentifier is the name of a field of that type.
The similarity of the names is entirely coincidental.
private DataIdentifier dataIdentifier;
DataIdentifier is a Type whereas dataIdentifier is a variable declared of that type
Like
private int a;
where int is a type and a is a variable of type Int
This question has been answered several times over, but I would like to instead recommend what I believe to be the BEST introductory book for C#. Even if you don't like learning from books, you'll like this one:
Head First C#
Check out the free chapters and if you like it, buy it. I guarantee you won't be sorry. Hope it helps.
DISCLAMER: I am in no way affiliated to OReilly Media or any of its subsidiaries... ;)
It is just another type of notation. It's really a silly variable name. I wouldn't recommend you follow the same convention. DataIdentifier is the class/object type. private is the access modifier.
The DataIdentifier is the type (class or struct) and dataIdentifer is the name.
DataIdentifier is the type of the variable
dataIdentifier is the name of the variable (it is of the type DataIdentifier)
C# is case sensitive. DataIdentifier and dataIdentifier are two different things.
Here DataIdentifier is the type and dataIdentifier is the variable.
It may be useful for you to relate the example to the actual grammar of C#.
field-declaration:
attributesopt field-modifiersopt type variable-declarators ;
field-modifiers:
field-modifier
field-modifiers field-modifier
field-modifier:
new
public
protected
internal
private
static
readonly
volatile
variable-declarators:
variable-declarator
variable-declarators , variable-declarator
variable-declarator:
identifier
identifier = variable-initializer
variable-initializer:
expression
array-initializer
Related
I ran into a problem while doing my job, which is porting software from flash AS3 to .NET/Mono. In AS3 code base I can find many Object declarations that are initialized like this:
private const MAPPING:Object =
{
ssdungf:'flydung',
ssdungt:'flydung',
superfutter:'superfeed'
}
The best option for me would be in C# using anonymous type like this:
var MAPPING = new
{
ssdungf = "flydung",
ssdungt = "flydung",
superfutter = "superfeed"
};
The problem is... well let me quote MSDN (source):
You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type
But they don't say why.
So the question remains: why you cannot declare a field and property as having an anonymous type? Why .NET creators stripped it from that option?
I am getting warning here from SO that my question appears subjective, but I think it is not at all - there need to be objective reason for that.
As for me, I don't see any obstacles for that but somehow it is not supported. As compiler can easily generate the type for field or property of class, in a same manner as it does for local variables.
The option for me was to use dynamic type but unfortunately Mono engine I am using is stripped from that.
Also the option for me is to use object type and using later reflection to find these fields:
private static readonly object MAPPING = new
{
ssdungf = "flydung",
ssdungt = "flydung",
superfutter = "superfeed"
};
But using reflection is this situation is dirty I would say.
I tried to find answer, but I really didn't find any. Here are some SO answers to similar questions, but they don't answer why:
Can a class property/field be of anonymous type in C# 4.0?
Declaring a LIST variable of an anonymous type in C#
How do you declare a Func with an anonymous return type?
Why you cannot declare a field and property as having an anonymous type?
Because C# is statically typed, so any memory location has to be given a type, and declaration does so. With locals we can infer from context if its initialised at the same time as declaration with var but that is a shorthand for a type that is usable even when the type hasn't got a name.
What would a field with an anonymous type, that is to say a statically-bound but indescribable type, mean?
dynamic would indeed be the closest analogy to the code you are porting, but since that isn't available to you, you might consider using an IDictionary<string, object> (which incidentally is how ExpandoObject, which is often used with dynamic to have objects that behave more like javascrpt objects, works behind the scenes). This would be slower and less type-safe than if you created a class for the object needed, but can work.
The problem on an anoynmous property is: how do you get/set it?
Suppose it would work:
class MyClass
{
public MyField = new { TheValue = "Hello World" };
}
Now in your consuming code you´d write code to read the code:
MyClass m = new MyClass();
m.MyField.TheValue = "newValue";
How was this different from having a type for MyField? All you´d get is that you can omit two or three lines of code whilst gaining nothing. But I think you might produce many problems as no-one knows what he can assign to/expect from that member.
Furthermore you can´t do much with an anonymous object, basically you can just set it and read it. There are no methods (except Equalsand GetHashCode inherited from object) that you can call so the opportunities are quite low.
Last but not least an anonymous object is usually used as temporaryily, for example within a Select-statement. When you use it you say: this type is going to be used only within the current specific scope and can be ignored by the entire world as internal implementation-detail. Creating a property of an anonymous type will expose such a detail to the outside. Of course you could argue that the designers could at least allow them for private members, but I guess doing so would bypass the complete concept of accessability for nothing.
This question already has answers here:
When do you use the "this" keyword? [closed]
(31 answers)
Closed 9 years ago.
In the following constructor, is the 'this' keyword required? I know I can remove it, it complies and everything is okay. If I omit 'this' will that cause problems for me down the road? Is ommission of 'this' considered bad practice?
// Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}
No, this is purely optional in almost all cases. The only reason it is required in your example is to disambiguate between local variables and parameters and member variables that happened to have the same identifier name.
You could avoid the use of this by renaming either the parameter or the field to something unique.
Yes, you need it in your code example. C# will always assume you mean local variable, so if a member variable and a local variable exist with the same name, you must use this, otherwise it will be assumed that you are referring to the local variable.
In your code example, if you neglect the this, you are effectively assigning name (or alias)'s value to itself (thus accomplishing nothing).
in the case below this is absolutely required. But you can get around it by choosing variable names carefully. In my humble opinion, there is nothing wrong with the example below and I do not mind having to use this. In fact, I often use this even when it is not required just to prompt intellisense and auto-complete in my IDE.
internal class Something
{
private string name;
public Something(string name)
{
this.name = name;
}
}
It's optional, unless you have a member variable named 'name', in that case, your line there will be assigning to itself.
I always like to access all member variables with "this", just to be explicit. Some people like to use "_" as a prefix, or even "m".
In C# it is most common to either name the private variable _Name or m_Name. This also makes it easy to visually match up Properties because if you have a property Name, which uses a local private variable _Name, it is easy to see quickly what it is for.
Without the this keyword in your example, all you are doing is assigning the local variable to the local variable (and not to the private variable). Which is why it compiles, but won't do what you think it is doing.
in your example, if you don't use "this" something worse will happen: "Variable Hiding"
I have started learning C# and object oriented programming and I must admit it's really fun. Now, as I was learning about inheritance and polymorphism, the following thought crossed my mind and I tried to make it work in code and see the results. I'll post the code and then ask specific questions so that it'll be easier for anyone answering to follow the train of thought that I had.
class Program
{
public static void Main(string[] args)
{
B b = new B();
b.b = 5;
A a = b;
Console.WriteLine(a.b);
}
}
class A
{
}
class B : A
{
public int b;
}
Now, when I try and run the above code, it gives me a compile time error saying "'ConsoleApplication1.A' does not contain a definition for 'b' and no extension method 'b' accepting a first argument of type 'ConsoleApplication1.A' could be found". Essentially what I understand this means is that the member variable b is not accessible.
However, if I comment out the Console.WriteLine() and execute in Debug mode and hover over the a variable declared as 'A' class type, the object it points to does have a member variable b with the value of 5.
My question is -
Why isn't the member variable accessible for the a variable of class type A? (I'll admit I sort of understand that at compile time the compiler doesn't know that the object being assigned to the variable 'a' has the member variable b which is assigned the value 5, which brings me to my next question)
Is this some sort of inherent flaw in the concept of inheritance that although objects of the base class have members of the derived class, they cannot be accessed because they are assigned to variables of base class type?
Your self-answer in the first bullet point is correct: the compiler doesn't look at what values have been assigned to a variable when working out what members are available. It only cares about the compile-time type of the variable. It's not about whether the b variable is "accessible" in the normal sense (public, private, internal etc) - it's about whether the member is even considered to exist as far as the compiler is concerned. You're using an expression of type A, so when the compiler tries to resolve member b, it simply doesn't find it.
As for your second bullet point: no, I don't see that as an inherent flaw at all. Arguably it's a benefit, in that it makes you think about the level of abstraction you're trying to work at. That in turns allows you to replace one implementation of that abstraction with another. If you could always (somehow) access the derived type's members, then if you later wanted to replace the value with an instance of a different derived type, your code could break. If you want to depend on the value of a being a B reference, then simply declare the variable as being of type B rather than A. By declaring the variable using type A, you're explicitly saying "I don't care what the implementation is; I only care about using this object from the perspective of it being an A."
There's one way round this in C# though: using dynamic instead. That way, all member access is resolved at execution time instead of compile time, and acts on the execution-time type of the dynamically-typed variable. (Or rather, whatever view of that you would normally have access to, following the normal access control rules.)
For example:
B b = new B();
b.b = 5;
dynamic a = b;
Console.WriteLine(a.b);
That will compile and run. Of course, it's not very safe, because you could equally have:
Console.WriteLine(a.typoInMemberName);
... which will still compile, but fail at execution time. This is one downside of using dynamic typing.
You can see the variable by casting a to B. (a as B).b You cannot access members that are not declared. Only if class is dynamic like ViewBag. It is so because of strict typing in C# and is not really about OOP. In PHP's OOP the code you posted is valid.
It isn't accessible "in that context". The context being a type "A" context, so it has no field "b".
Cast it to a "B" and you can access public fields.
A a = b;
Console.WriteLine((a as B).b);
In this case, it isn't about accessibility (member access), it is about type signature. What is an "A"? An "A" doesn't have a .b field. however, if you use reflection to examine the "a" object, you should find the field, if it is really of type "B".
It isn't a flaw. Consider an alternative. What if "A" did have a "b" field, but you redefined the "b" field in class "B" (shadowing). What would you expect the compiler to do? Which .b is correct? The one dictated by the type context.
I know it can't be done since using var can only be done for local variables. I'm just wondering if anyone has a theory why the C# team thought this should be so. e.g. what would be wrong with this:
public class SomeClass
{
var someString = "hello"; //not cool
public SomeClass()
{
var someOtherString = "hello"; //cool
}
}
If someString is initialised then it is obviously a string just like someOtherString. Why is there one rule for local variables and another for globals?
Duplicate, hence CW.
See the posting by Eric Lippert:
Let me give you a quick oversimplification of how the C# compiler works. First we run through every source file and do a "top level only" parse. That is, we identify every namespace, class, struct, enum, interface, and delegate type declaration at all levels of nesting. We parse all field declarations, method declarations, and so on. In fact, we parse everything except method bodies; those, we skip and come back to them later.
[...]
if we have "var" fields then the type of the field cannot be determined until the expression is analyzed, and that happens after we already need to know the type of the field.
Its to do with the amount of searching the compiler would have to do resolve the type.
This question already has answers here:
When do you use the "this" keyword? [closed]
(31 answers)
Closed 9 years ago.
In the following constructor, is the 'this' keyword required? I know I can remove it, it complies and everything is okay. If I omit 'this' will that cause problems for me down the road? Is ommission of 'this' considered bad practice?
// Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}
No, this is purely optional in almost all cases. The only reason it is required in your example is to disambiguate between local variables and parameters and member variables that happened to have the same identifier name.
You could avoid the use of this by renaming either the parameter or the field to something unique.
Yes, you need it in your code example. C# will always assume you mean local variable, so if a member variable and a local variable exist with the same name, you must use this, otherwise it will be assumed that you are referring to the local variable.
In your code example, if you neglect the this, you are effectively assigning name (or alias)'s value to itself (thus accomplishing nothing).
in the case below this is absolutely required. But you can get around it by choosing variable names carefully. In my humble opinion, there is nothing wrong with the example below and I do not mind having to use this. In fact, I often use this even when it is not required just to prompt intellisense and auto-complete in my IDE.
internal class Something
{
private string name;
public Something(string name)
{
this.name = name;
}
}
It's optional, unless you have a member variable named 'name', in that case, your line there will be assigning to itself.
I always like to access all member variables with "this", just to be explicit. Some people like to use "_" as a prefix, or even "m".
In C# it is most common to either name the private variable _Name or m_Name. This also makes it easy to visually match up Properties because if you have a property Name, which uses a local private variable _Name, it is easy to see quickly what it is for.
Without the this keyword in your example, all you are doing is assigning the local variable to the local variable (and not to the private variable). Which is why it compiles, but won't do what you think it is doing.
in your example, if you don't use "this" something worse will happen: "Variable Hiding"