开发者

Does C# use the -> pointer notation?

I am trying to learn C# and I am familiar with the C++ struct pointing notation ->. I was curious if that crossed over into C#.

Example:

someStruct->开发者_如何学CsomeAttribute += 1;


There is pointer notation in C#, but only in special cases, using the unsafe keyword.

Regular objects are dereferenced using ., but if you want to write fast code, you can pin data (to avoid the garbage collector moving stuff around) and thus "safely" use pointer arithmetic, and then you might need ->.

See Pointer types (C# Programming Guide) and a bit down in this example on the use of -> in C#.

It looks something like this (from the last link):

struct MyStruct 
{ 
    public long X; 
    public double D; 
}

unsafe static void foo() 
{
   var myStruct = new MyStruct(); 
   var pMyStruct = & myStruct;

   // access:

   (*pMyStruct).X = 18; 
   (*pMyStruct).D = 163.26;

   // or

   pMyStruct->X = 18; 
   pMyStruct->D = 163.26;
}


C# doesn't differentiate between pointers and references. In effect everything is a reference so uses the . notation.

Edit: as is pointed out in the comments below it's not as simple as that. There are reference types and value types. What I meant above is that there is no distinction between reference types and pointer types.

Edit2: Although apparently there is if you're using the unsafe parts of c#! I've learnt something today!


It's interesting that C# decided to use . rather than -> to reference a member of an object referred to by a class reference, since the semantics are closer to those of C's -> operator than its . operator. For example, in C, if one sees the code a=b; a.X=5; one would recognize that it's writing to field X of some struct a, which is a different struct from b. By contrast, if one sees the code a=b; a->X=5; one would recognize that it's writing to field X of the struct pointed to by both a and b. In C#, the behavior of the code in question would depend upon whether the type of b is a class or a struct.

The addition of generics to C#, however, would have been difficult if C# had used different dereferencing operators for class and struct types, since it's possible for a particular piece of code to dereference an instance of an interface- constrained type without knowing whether the type in question is a struct or a class; it's unclear which operator should be used if structs used a different operator from classes.


While C# has pointers behind the scenes they are totally hidden from the user. You can't get at a pointer to dereference it. You only have the dot notation to access something inside something, whether the original is a pointer or not is hidden from you.

The only way you are even aware of pointers is things that pass by reference rather than passing by value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜