Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am a newbie with a piece of code that wont run like its example. Even the example code cut and pasted in my IDE wont work. The output is always red twice.
C#
using System;

namespace MyApplication
{
    class Car
    {
        string color = "red";
        int maxSpeed = 200;

        static void Main(string[] args)
        {
            Car myObj = new Car();
            Console.WriteLine(myObj.color);
            Console.WriteLine(myObj.maxSpeed);
        }
    }
}


What I have tried:

retyping
changing attributes and variables
copy paste the original code example
Posted
Updated 15-Dec-19 22:19pm
v3
Comments
Mohibur Rashid 15-Dec-19 17:05pm    
Please learn about access modifier. Bu default class members are private. And copy paste is not the best way to learn.
Maciej Los 16-Dec-19 4:07am    
Where from you get this piece of code?

Before you start using someone's code, i'd strongly recommend to start with basics. An MSDN documentation[^] is the place where you can start. You can also buy a book or find online tutorial...

If you would like to know how to create your first console applicationa with custom class, please follow this: Classes - C# Programming Guide | Microsoft Docs[^]
 
Share this answer
 
Try like this:
using System;

namespace MyApplication
{
	class Program
	{
		static void Main(string[] args)
		{
				Car myObj = new Car();
				Console.WriteLine(myObj.color);
				Console.WriteLine(myObj.maxSpeed);
		}

		public class Car
		{
			public string color = "red";
			public int maxSpeed = 200;
		}
	}
}

It's also possible to put the Car class outside the Program class:
class Car
{
    public string color = "red";
    public int maxSpeed = 200;
}

In fact it is recommended to put each class in it's own file, but for such a small example it is not necessary.
Note that the use of Access modifiers like Public for a class differs when using a Console or Winforms application, the Console application sometimes does not like it.
 
Share this answer
 
v3

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