Reputation: 115
Here is the code of .net framework 4.0. But our old system is using 3.5. It's difficult to upgrade all the codes. I want to know how to change the codes written by 4.0 to 3.5 codes.
The main problem is I don't know how to convert "return string.Join(",", states);" Error happened when I was trying to compile it using .net framework 3.5.
Thank you!
public enum States
{
....
}
public static string GetStates(uint stateFlags)
{
var stateList = Enum.GetValues(typeof(States));
var states = default(States);
foreach (var state in stateList)
{
if (state == null) continue;
var stateEnum = (States)state;
if (HasState(stateFlags, stateEnum))
{
states = states | stateEnum;
}
}
return string.Join(",", states);
}
The error is Error The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments
Upvotes: 0
Views: 593
Reputation: 13495
Here is a slightly modified version of your original solution
public enum States
{
None = 0,
StateOne = 1,
StateTwo = 2,
StateThree = 4,
StateFour = 8,
};
public static string GetStates(uint stateFlags)
{
var stateList = Enum.GetValues(typeof(States));
List<States> states = new List<States>();
foreach (int state in stateList)
{
if ((stateFlags & state) != 0)
{
states.Add((States)state);
}
}
return string.Join(",", states);
}
Running
GetStates((uint)(States.StateOne | States.StateTwo))
outputs
StateOne,StateTwo
Upvotes: 1
Reputation: 115
Thank you everybody for your warmly help. I changed the last line to below:
var valuesAsList = GetValues(states).Cast<string>().ToList();
return string.Join(",", valuesAsList.ToArray());
And added the method:
public static IEnumerable<Enum> GetValues(Enum enumeration)
{
List<Enum> enumerations = new List<Enum>();
foreach (FieldInfo fieldInfo in enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))
{
enumerations.Add((Enum)fieldInfo.GetValue(enumeration));
}
return enumerations;
}
The compile error disappeared, but I still haven't test the code to see whether it's the same result with .net 4.0.
Thanks again.
Upvotes: 0
Reputation: 18832
string.Join
in .Net 3.5 only supports a string array whereas .Net 4.0 has additional overloads to work with IEnumerable<string>
or Object[]
.
You should be passing a string[]
to the Join
method.
More at the MSDN docs:
.Net 4 : http://msdn.microsoft.com/en-us/library/dd992421(v=vs.100).aspx
.Net 3.5: http://msdn.microsoft.com/en-us/library/57a79xd0(v=vs.90).aspx
Upvotes: 5
Reputation: 10456
In .Net 3.5 the overload you used for "String.Join" is not available. Replace your return row with the following 2 rows:
string[] stateNames = Enum.GetNames(typeof(States));
return string.Join(",", stateNames);
The expected second argument is an array of Strings.
Upvotes: 1