Reputation:
Shamed by this simple question. For some reason, I want to put all asp.net URLs in an enum. But I got an error: identifer expected
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Admin.Code
{
public enum url
{
/_layouts/Admin/test1.aspx,
/_layouts/Admin/test2.aspx,
/_layouts/Admin/test3.aspx
}
class AdminUrlSettings
{
}
}
Thanks.
Upvotes: 2
Views: 2728
Reputation: 1456
These aren't valid enum identifiers. You'll need string enumerations. Here's an example
You will be able to do something like this:
public enum url
{
[StringValue("/_layouts/Admin/test1.aspx")]
Test1,
[StringValue("/_layouts/Admin/test2.aspx")]
Test2,
[StringValue("/_layouts/Admin/test3.aspx")]
Test3
}
Upvotes: 2
Reputation: 71573
Here's something I've done many times to turn enumerated values into "friendly strings". You can also use it to create "string-valued" enums. It's in the same vein as Msonic's solution, but the attribute is built into the Framework.
public enum url
{
[Description(@"/_layouts/Admin/test1.aspx")] Test1,
[Description(@"/_layouts/Admin/test2.aspx")] Test2,
[Description(@"/_layouts/Admin/test2.aspx")] Test3
}
...
public static string GetDescription(this Enum enumValue)
{
object[] attr = enumValue.GetType().GetField(enumValue.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false);
if (attr.Length > 0)
return ((DescriptionAttribute) attr[0]).Description;
return enumValue.ToString();
}
//usage
Response.Redirect(url.Test1.GetDescription());
Upvotes: 3
Reputation: 754763
Identifiers in C# can't contain /
characters. They are limited to underscores, letters and numbers (and possibly a @
prefix). To fix this you need to make the enum values valid C# identifiers
enum url {
test1,
test2,
test3
}
Later turning these into an actual valid url can be done with a switch statement over the value
public static string GetRelativeUrl(url u) {
switch (u) {
case url.test1:
return "/_layouts/Admin/test1.aspx";
case url.test2:
return "/_layouts/Admin/test2.aspx";
case url.test3:
return "/_layouts/Admin/test3.aspx";
default:
// Handle bad URL, possibly throw
throw new Exception();
}
}
Upvotes: 1
Reputation: 995
Enums don't really work like that. Valid identifiers work the same way variable names do (ie. a combination of letters, numbers and underscores not beginning with a number). Why not just use a list:
List<string> urls = new List<string>{"/_layouts/Admin/test1.aspx", "/_layouts/Admin/test2.aspx", "/_layouts/Admin/test3.aspx"}
or use slightly different identifiers:
public enum url
{
layout_Admin_test1,
layout_Admin_test2,
layout_Admin_test3
}
Upvotes: 0