how to convert a string to a ushort

Jonathan Connery picture Jonathan Connery · Jul 24, 2017 · Viewed 9.1k times · Source

I have researched all of the questions that match my query and tried their solutions however none appear to work for me so I am asking how I convert a string to a ushort I have this set up all ready

public static string vid
{
    get { return "<vehicleid>"; }
}

I've tried to use this : short[] result = vid.Select(c => (ushort)c).ToArray(); but when I go to put the vid ushort into this bit

[RocketCommand("vehicle", "This command spawns you a vehicle!", "<vehicleid>", AllowedCaller.Player)]
public void ExecuteCommandVehicle(IRocketPlayer caller, string[] command)
{
    UnturnedPlayer spawner = (UnturnedPlayer)caller;
    spawner.GiveVehicle(vid);
}

I get the following error :

Severity Code Description Project File Line Suppression State Error CS1503 Argument 1: cannot convert from 'string' to 'ushort' arena v by FridgeBlaster C:\Users\Jonathan\Documents\Visual Studio 2015\Projects\arena v by FridgeBlaster\arena v by FridgeBlaster\vehicle.cs 71 Active

Answer

Mateusz picture Mateusz · Jul 24, 2017

What you're looking for is ushort.TryParse or ushort.Parse methods.
I would suggest using this piece of code :

ushort[] result = vid.Where(i => ushort.TryParse(i, out short s)).Select(ushort.Parse);

Or if you do not use latest C# version :

ushort[] result = vid.Where(i => { ushort r = 0; return ushort.TryParse(i, out r); }).Select(ushort.Parse);

Okay so the problem ( as what your error says ) is that your GiveVehicle method accepts ushort as an argument and you're putting string type in it. Try doing something like this :

ushort val = 0;
if(ushort.TryParse(vid, out val))
{
    UnturnedPlayer spawner = (UnturnedPlayer)caller;
    spawner.GiveVehicle(val);
}

Based on this source which is responsible for calling method marked with RocketCommand attribute. Your <"vehicleid"> is/should be stored in a command array on first place. So to get this out and convert use something like this :

if(command.Length > 0)
{
    ushort val = 0;
    if(!string.IsNullOrWhiteSpace(command[0]) && ushort.TryParse(command[0], out val))
    {
        UnturnedPlayer spawner = (UnturnedPlayer)caller;
        spawner.GiveVehicle(val);
    }
}