Classes & Models
Create a class, give it properties and a constructor, and use it — the C# version of a Laravel model.
#csharp #dotnet #classes #models
A "model" in C# is just a class that holds data. There's no base Model to
extend and no database magic (that's EF Core's job later) — a plain class is
your model.
Create a model
Each class usually lives in its own file named after the class. A User
model goes in User.cs:
namespace MyApp.Models;
public class User
{
// Properties — these are the "columns". Note the { get; set; }
public int Id { get; set; }
public string Username { get; set; } = "";
public string Password { get; set; } = "";
public bool IsActive { get; set; } = true;
}
{ get; set; } is an auto-property — C#'s way of declaring a readable and
writable field. It's the equivalent of a public property in a Laravel model,
but explicit. = "" gives it a default so it doesn't start as null.Constructors
A constructor runs when you create the object — same role as PHP's
__construct. Use it to require values up front:
public class User
{
public string Username { get; set; }
public string Password { get; set; }
// Constructor — same name as the class, no return type
public User(string username, string password)
{
Username = username;
Password = password;
}
}
Use the model
You create an object with new. This is where using pulls in the namespace so
the type is visible (more on that in Project structure):
using MyApp.Models;
// with a constructor
var user = new User("ada", "secret");
// or with object-initialiser syntax (no constructor needed)
var admin = new User
{
Username = "admin",
Password = "hunter2",
IsActive = true
};
Console.WriteLine(user.Username); // read a property
user.IsActive = false; // set a property
Methods on a model
A model can have behaviour too, not just data:
public class User
{
public string Username { get; set; } = "";
public string Password { get; set; } = "";
public bool CheckPassword(string attempt)
{
return Password == attempt; // (hash this for real — plain text is just for the example)
}
}
if (user.CheckPassword("secret"))
{
Console.WriteLine("Match");
}
Laravel → C# cheat
| Laravel model | C# class |
|---|---|
class User extends Model | public class User (no base needed) |
$user->name | user.Name |
__construct(...) | public User(...) { } |
protected $fillable | just declare the properties you want |
new User(['name' => 'Ada']) | new User { Name = "Ada" } |
Next
Move shared behaviour off the model and into reusable files → Services & helpers.
C# Basics
Types, variables, control flow and how to write a function (method) in C#, mapped from PHP.
Services & Helpers
Put code in another file — a service or a static helper — and call it from anywhere, the C# way.