开发者

Inconsistent syntax c#?

开发者 https://www.devze.com 2022-12-27 08:02 出处:网络
private string[] GetRoles() { string[] foo = {\"Test\"}; return foo; } The above compiles, but... private string[] GetRoles()
private string[] GetRoles()
{
    string[] foo = {"Test"};
    return foo;       
}

The above compiles, but...

private string[] GetRoles()
{
    return {"Test"};        
}

Does not.

Replacing it with:

return new string[] { "Te开发者_开发知识库st" };    

Will obviously compile though. Is this inconsistancy or am i being stupid, or am i just wrong :S.


Attributed to @Luke:

The first example is just shorthand array initialization syntax. The second example is simply not legal C# syntax.


The array object must be created before you return as value.So

return new string[]{"Test"};

Give you the right return type.


Your snippet doesnt work for the same reason the below code does not work (as in does not compile)

private string[] GetRoles()
{
    //string[] foo = {"Test"};
    var foo = {"Test"};
    return foo;       
}

in your first snippet, the string[] gives the compiler enough information to allow the sugar to function


Historically you had to write new operator. Like this:

string[] foo = new string[] {"Test"};

I think that it was in C# 2.0 that it was made possible to omit the new operator and write simply:

string[] foo = {"Test"};

where compiler can figure out that you are initializing an array. And I think I agree with you that this is an inconsistency. When the possibility to omit new operator was added they probably forgot about return statement as it's very rare to return array that was initialized inside return statement. Because when compiler looks at the return type it should be able to figure it out as well as in a case of assignment.

Personally I never omit new operator so I never even thought about it :)


private string[] GetRoles()
{
    string[] foo = {"Test"};
    return foo;       
}

In the example above you are creating a new string[] array and then initialising it with one element called "Test".

private string[] GetRoles()
{
    return {"Test"};        
}

In this example you have created a method that expects to return a string array. However, you are at no point creating a new string array[]* object. Before you can add elements to an array you need to first create it. You are basically trying to returns elements from a non-existent array, which is why it fails.

You could argue the compiler could create the array for you, but it doesn't do that in your first example, so why expect it to do it in the second?

0

精彩评论

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