0
0
C Sharp (C#)programming~5 mins

Built-in attributes (Obsolete, Serializable) in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Built-in attributes add extra information to your code. Obsolete warns when code is old. Serializable marks data that can be saved or sent.

You want to tell others not to use a method because it will be removed soon.
You need to save an object to a file or send it over the network.
You want to keep your code clean by marking old parts clearly.
You are working with data that must be transferred between programs.
You want to avoid mistakes by warning about outdated code.
Syntax
C Sharp (C#)
[Obsolete("message", isError)]
[Serializable]
class ClassName
{
    // class members
}

Obsolete can show a warning or error when used.

Serializable allows objects to be converted to a format for storage or transfer.

Examples
This marks OldMethod as outdated and shows a warning with a message.
C Sharp (C#)
[Obsolete("Use NewMethod instead.")]
void OldMethod() { }
This marks DangerousMethod as obsolete and causes a compile error if used.
C Sharp (C#)
[Obsolete("Do not use this method.", true)]
void DangerousMethod() { }
This marks the Person class so its objects can be saved or sent.
C Sharp (C#)
[Serializable]
class Person
{
    public string Name;
    public int Age;
}
Sample Program

This program shows how Obsolete warns about old code and Serializable marks a class for saving data.

C Sharp (C#)
using System;

[Obsolete("Use NewMethod instead.")]
class OldClass
{
    public void OldMethod()
    {
        Console.WriteLine("Old method running.");
    }
}

[Serializable]
class Data
{
    public int Number;
}

class Program
{
    static void Main()
    {
        OldClass obj = new OldClass();
        obj.OldMethod();

        Data d = new Data();
        d.Number = 42;
        Console.WriteLine($"Data number: {d.Number}");
    }
}
OutputSuccess
Important Notes

Using [Obsolete] helps keep your code clean by warning about old parts.

[Serializable] is needed before saving or sending objects.

You can customize the Obsolete message to guide users.

Summary

Obsolete warns or errors when old code is used.

Serializable marks classes so their objects can be saved or transferred.

These attributes help keep code safe and clear.