How to create Custom C# Code snippet in Visual Studio 2022 or for any version of Visual Studio.
Step 1: XML File Create Karna
- Ek .snippetfile banaiye. Iska extension.snippethoga.
- File ke andar aapko ek specific XML structure likhna hoga. Example:
Repository Snippet Example:
<CodeSnippet xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>Repository Snippet</Title>
    <Shortcut>repo</Shortcut>
    <Description>Generic repository implementation.</Description>
    <Author>YourName</Author>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>T</ID>
        <ToolTip>Entity type</ToolTip>
        <Default>MyEntity</Default>
      </Literal>
    </Declarations>
    <Code Language="csharp">
      <![CDATA[
using Microsoft.EntityFrameworkCore;
public class Repository<$T$> : IRepository<$T$> where $T$ : class
{
    private readonly DbContext _context;
    private readonly DbSet<$T$> _dbSet;
    public Repository(DbContext context)
    {
        _context = context;
        _dbSet = _context.Set<$T$>();
    }
    public async Task<IEnumerable<$T$>> GetAllAsync()
    {
        return await _dbSet.ToListAsync();
    }
    public async Task<$T$> GetByIdAsync(int id)
    {
        return await _dbSet.FindAsync(id);
    }
    public async Task<$T$> AddAsync($T$ entity)
    {
        await _dbSet.AddAsync(entity);
        await _context.SaveChangesAsync();
        return entity;
    }
    public async Task<$T$> UpdateAsync($T$ entity)
    {
        _dbSet.Attach(entity);
        _context.Entry(entity).State = EntityState.Modified;
        await _context.SaveChangesAsync();
        return entity;
    }
    public async Task<bool> DeleteAsync(int id)
    {
        var entity = await GetByIdAsync(id);
        if (entity == null) return false;
        _dbSet.Remove(entity);
        await _context.SaveChangesAsync();
        return true;
    }
}
]]>
    </Code>
  </Snippet>
</CodeSnippet>
Step 2: Snippet file ko Folder Me Save Karna
1. Is 
.snippet file ko Visual Studio snippets folder me save karna hoga.
Path:C:\Users\<YourUsername>\Documents\Visual Studio <Version>\Code Snippets\Visual C#\My Code Snippets
replace YourUsername = windows user name (lenovo), Version = 2022
C:\Users\LENOVO\Documents\Visual Studio 2022\Code Snippets\Visual C#\My Code Snippets
2. Agar 
My Code Snippets folder nahi hai, to aap manually create kar sakte ho.Step 3.  restart your PC. 
Step 4. open any cs file type repo + tab + tab key press you get Repository code.
How to create Custom C# Code snippet in Visual Studio 2022 or for any version of Visual Studio
![How to create Custom C# Code snippet in Visual Studio 2022 or for any version of Visual Studio]() Reviewed by Rikesh
        on 
        
December 27, 2024
 
        Rating:
 
        Reviewed by Rikesh
        on 
        
December 27, 2024
 
        Rating: 
       
No comments: