Click here to Skip to main content
14,921,143 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
when i run this code i get ClassA does not exists. how do i access const int aaa ?
code

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace const2
{
    public class ClassA
    {
        public const int aaa = 10;
    }

    class Program
    {
        static void Main(string[] args)
        {
            ClassA classaa = new ClassA();

            Console.WriteLine(classA.aaa);
            Console.ReadKey();
        }
    }
}
Posted
Updated 6-Oct-16 3:00am
v2
Comments
[no name] 5-Oct-16 14:28pm
   
"when i run this code i get ClassA does not exist", uhm.... no it does not. Your code will not run at all because it won't compile. And the error you see on your screen tells you what the problem is. You are trying to access a non static class/field/property from a static context. Make your ClassA static and your aaa static. And for the future, include accurate information in your postings.
Afzaal Ahmad Zeeshan 5-Oct-16 17:14pm
   
That is because of a typo in your program, you need to write classaa instead of the classA.

There are a few things wrong here: mainly to do with C# being case sensitive: "classA" is not the same as "ClassA", so you can't access the const value without getting the class name right:
C#
ClassA classaa = new ClassA();
Console.WriteLine(ClassA.aaa);

Because it is a const value, it is implicitly static - so you can't access it via a class instance, only via the class name. So the instance you declare is unnecessary, as this won't work either:
C#
ClassA classaa = new ClassA();
Console.WriteLine(classaa.aaa);
   
Comments
Afzaal Ahmad Zeeshan 5-Oct-16 17:11pm
   
5ed.
spell error, first char is in uppercase

C#
Console.WriteLine(ClassA.aaa);
   
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace const2
{
    public static class ClassA
    {
        public const int aaa = 10;
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(aaa);
        }
    }
}

Untested, but accurate for accessing the const.
   

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