Introduction
A class groups related data and actions together. It helps organize code like a blueprint for objects.
Jump into concepts and practice - no test required
A class groups related data and actions together. It helps organize code like a blueprint for objects.
class ClassName { // Fields, properties, methods, constructors }
Class names usually start with a capital letter.
Curly braces { } define the class body where you put data and actions.
Car with no content yet.class Car { // Car details go here }
Person with two fields: Name and Age.class Person { public string Name; public int Age; }
Dog with a method Bark that prints a sound.class Dog { public void Bark() { Console.WriteLine("Woof!"); } }
This program defines a Book class with two fields and a method to show info. In Main, it creates a book object, sets its data, and prints it.
using System; class Book { public string Title; public string Author; public void DisplayInfo() { Console.WriteLine($"Title: {Title}, Author: {Author}"); } } class Program { static void Main() { Book myBook = new Book(); myBook.Title = "The Little Prince"; myBook.Author = "Antoine de Saint-Exupéry"; myBook.DisplayInfo(); } }
Class members can be fields (data) or methods (actions).
Use public to allow access from outside the class.
Classes are templates; you create objects (instances) from them.
Classes group data and behavior into one unit.
Use class ClassName { } to declare a class.
Inside, define fields and methods to describe the object.
Car in C#?class followed by the class name and curly braces.class Car { }, which is the correct syntax for declaring a class named Car.class 123Car { }, which starts with digits, causing a syntax error.class Dog {
public string Name = "Buddy";
}
class Program {
static void Main() {
Dog d = new Dog();
System.Console.WriteLine(d.Name);
}
}Name initialized to "Buddy".d.Name is printed, so output is "Buddy".class Book
{
string title;
void SetTitle(string t)
{
title = t;
}
}title and method SetTitle lack access modifiers like private or public, which can cause confusion or errors in some contexts.Student with a field name and a method GetName that returns the student's name. Which is the correct complete class declaration?name and method GetName should be public to be accessible outside the class.GetName returns a string, so its return type must be string and it must return name.name as public string and GetName as public string method returning name.