Click here to Skip to main content
15,899,026 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
When i run this code all i get is
C#
the name pet does not exists in the current context


and i am following this tutorial s[^] step by step not sure what is going on .


using System;

class Program
{
    enum PetType
    {
        None,
        Cat = 1,
        Dog = 2
    }

    static void Main()
    {
        // A.
        // Possible user input:
        string value = "Dogfff";

        // B.
        // Try to convert the string to an enum:



        try { PetType pet = (PetType)Enum.Parse(typeof(PetType), value); }

        catch (Exception ex)
        {

            Console.WriteLine(ex.Message);


            pet = PetType.None;
        }

        // C.
        // See if the conversion succeeded:
        if (pet == PetType.Dog)
        {
            Console.WriteLine("Equals dog.");
        }
    }
}


What I have tried:

************************************************
*
*
*******************************************************************************************************************
Posted
Updated 6-Oct-16 21:37pm
Comments
[no name] 6-Oct-16 20:37pm    
You need to read a basic programming book on variable scope. You have declared "pet" in the try block scope and you are trying to use it outside of the try block. pet is out of scope.
[no name] 6-Oct-16 23:46pm    
"and i am following this tutorial s[^] step by step not sure what is going on ."
No you aren't. You changed the code and surprise surprise it doesn't work. You even know what you changed and the error message confirms it. Stick to the tutorial until you know what you are doing.
forte74 7-Oct-16 14:24pm    
this reply doesnt help much anyways... if you can be a little bit more clearer it would help
[no name] 7-Oct-16 17:54pm    
The code you show in your question is not the code in the example given in your link. The code in the link works and the differences introduced by you do not. I'm not sure how much clearer that can be put.
The Praveen Singh 7-Oct-16 2:44am    
Declare pettype outside try block

1 solution

As Suvendu Shekhar Giri already pointed out, your PetType instance, namely pet is bad scoped: it is accessible just inside the try block.
You have to declare it before the try block and the instantiate it inside the try block itself.
C#
PetType pet;
try
{
   pet = ...


Please see: Variable and Method Scope in Microsoft .NET[^].

[update]
Fixed, thanks to Richard.
[/update]
 
Share this answer
 
v3
Comments
Richard MacCutchan 7-Oct-16 6:21am    
Double declaration!
CPallini 7-Oct-16 6:34am    
OOOOOOOOOOOOPS!
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900