Search code examples
c#asp.netprogramming-languages

Nullable Int Type to be associated with a value within a Loop - What is your favourite approch?


I use C# and ASP.NET.

I use this code pasted below in my application with no problems, but I would like to know if there is a better way to achieve the same result.

What I need to do:

I need set a variable int imageId using a Loop. Variable imageId it is outside the Loop so can be used in other part of my code.

My questions:

  • Why if I use just int imageId; the compiler complain (ERROR: Use of unassigned local variable 'imageId' )?
  • I use a nullable int type instead of an int imageId = 0; so I can set it on a null value .. (to me seems semantically correct) would you recommend that? If no why.
  • What is you favorite approach to this kind of problem?

Thanks guys for your support!!!!

           int? imageId = null;
            foreach (DictionaryEntry valueEntry in e.Keys)
            {
                if (valueEntry.Key.Equals("ImageContentId"))
                {
                    imageId = Convert.ToInt32(valueEntry.Value.ToString());
                    break;
                }
            }

Please give me a sample of your code thank!


Solution

  • You could use the IOrderedDictionary method Contains. This would allow you to drop the loop construct altogether. e.g.

    if( e.Keys.Contains("ImageContentId") )
    {
        imageId = Convert.ToInt32( e.Keys["ImageContentId"].ToString() );
    }
    

    Also if you know that the Value is a string you might be interested in the Int32.TryParse method e.g.

    int imageId ;
    if( Int32.TryParse(e["ImageContentId"].ToString(), out imageId ) )
    { }
    

    The only reason that you would want to use an int? is if the data you're manipulating could be uninitialised. If you're parsing data and it's garbage you have 2 options: (NB: This assumes that you don't want to be throwing Exceptions RE the bad data).

    1) Use a default value - This has the benefit of being inherently tolerant of bad data.

    2) Use the int? construct - This has the advantage of informing the rest of the code that the data in known to be bad and ensures that they are designed to cope with null values.

    As for which is better... that can only be answered within the constructs of the system. If you're performing interop with external dll's that don't support nullable types then the decision is pretty clear!

    As for the compiler error: if you're initializing imageId within an if statement there will be occasions where the initialization branch won't be taken e.g. a bad value. To ensure that imageId is always initialized, the compiler will force you to initialize it outside of a conditional code path. Generally I always try and initialize a variable when I declare it. e.g.

    int imageId = 0;