0

I have the following field definition in a class:

   public Nullable<System.Guid> GlobalId { get; set; }

I have another class with the following:

   public string GlobalId { get; set; }

I would like to put the value of from the field with type System.Guid into the string.

I tried to do this here:

        var questionIds = _questionsRepository.GetAll()
            .Where(m => m.Problem != null &&
            m.Problem.SubTopic != null &&
            m.Problem.SubTopic.Topic != null &&
            m.Problem.SubTopic.Topic.SubjectId == 1)
            .Select(m => new QuestionHeader { GlobalId = (string) m.GlobalId })
            .ToList();
        return questionIds;

But it's giving me an error saying:

   Cannot convert type 'System.Guid?' to 'string'

Can someone tell me how I could do this?

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • Please look at the docs for [Nullable(T).ToString](http://msdn.microsoft.com/en-us/library/9hd15ket(v=vs.110).aspx) – Steve Dec 26 '13 at 13:39
  • 1
    I'd recommend you to read some basic c# tutorials. you'll enjoy understand the reasoning behind a lot of "weird errors" – Letterman Dec 26 '13 at 14:03

7 Answers7

10

You can get the string representation of the GUID by calling ToString() on it.

As your GUID is nullable, check if it's null before calling ToString():

string myString = guid.HasValue ? guid.Value.ToString() : "default string value";
ken2k
  • 48,145
  • 10
  • 116
  • 176
  • 3
    According to http://stackoverflow.com/questions/2449008/nullable-tostring, there is no need if you want to represent no-value as empty string. – Euphoric Dec 26 '13 at 13:38
  • Well, this answer is still a good way to do it if one wants to have a default value. – DarkWanderer Dec 26 '13 at 13:41
  • @Euphoric @Euphoric True, but as you said it implies you get `string.Empty` in case it's null (and I don't know what the OP wants as a default value). – ken2k Dec 26 '13 at 13:42
3

You don't cast to string. You use ToString() method.

Like this:

GlobalId = m.GlobalId.ToString()
Euphoric
  • 12,645
  • 1
  • 30
  • 44
3

Just use ToString() method

Guid? g = null;    
string s = g.ToString();

in case of null it will return String.Empty otherwise you'll get string representation of your Guid

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
3

You can convert a Guid with .ToString():

Guid gid = Guid.NewGuid();

string myID = gid.ToString();

Or using

Convert.ToString

Like:

Guid gid = Guid.NewGuid();

string myID = Convert.ToString(gid);
Dalorzo
  • 19,834
  • 7
  • 55
  • 102
2

Use Convert.ToString instead of (string)

GlobalId =  Convert.ToString(m.GlobalId)
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1
GlobalId = m.GlobalId.ToString()
Denis
  • 3,653
  • 4
  • 30
  • 43
1
string Id = Guid.NewGuid().ToString();
Anarion
  • 2,406
  • 3
  • 28
  • 42