// Example: Hello World in C#
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
// Example: Declaring and Initializing Variables
int age = 30;
string name = "John";
using System;
public class Dog { private string name = string.Empty;
public string Name { get { return name; } set { name = value; } }
public void Bark() { Console.WriteLine("Woof!"); } }
// Adding a Program class with a Main method class Program { static void Main(string[] args) { Dog myDog = new Dog(); myDog.Name = "Buddy"; myDog.Bark(); // Output: Woof! } }
csharpCopy code
// Example: Creating and Using an Object in C#
Dog myDog = new Dog();
myDog.Name = "Buddy";
myDog.Bark();
// Output: Woof!
csharpCopy code
// Example: Creating a Class and Object
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Person person = new Person { Name = "John", Age = 30 };
csharpCopy code
// Example: Inheritance
public class Student : Person
{
public string StudentID { get; set; }
}
Student student = new Student { Name = "Mary", Age = 20, StudentID = "S12345" };
csharpCopy code
// Example: Polymorphism
public class Person
{
public virtual string Speak()
{
return "Hello!";
}
}
public class Student : Person
{
public override string Speak()
{
return "Hi, I'm a student!";
}
}
csharpCopy code
// Example: Encapsulation
public class Person
{
private int age;
public int Age
{
get { return age; }
set { if (value > 0) age = value; }
}
}