Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a code snippet to generate a method in C#?

I want to write a code snippet which does following thing, like if I have a class let's say MyClass:

   class MyClass
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }

so the snippet should create following method:

 public bool DoUpdate(MyClass myClass)
  {
        bool isUpdated = false;
        if (Age != myClass.Age)
        {
            isUpdated = true;
            Age = myClass.Age;
        }
        if (Name != myClass.Name)
        {
            isUpdated = true;
            Name = myClass.Name;
        }
        return isUpdated;
    }

So the idea is if I call the snippet for any class it should create DoUpdate method and should write all the properties in the way as I have done in the above example.

So I want to know :

  1. Is it possible to do the above ?
  2. If yes how should I start, any guidance ?
like image 867
Embedd_0913 Avatar asked Sep 01 '12 18:09

Embedd_0913


People also ask

What is a code snippet in C?

Snippet is a programming term for a small region of re-usable source code, machine code, or text. Ordinarily, these are formally defined operative units to incorporate into larger programming modules. Snippet management is a feature of some text editors, program source code editors, IDEs, and related software.

How do you declare a function in C?

Function Declarations The actual body of the function can be defined separately. int max(int, int); Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

What is a function in C and give a small code snippet as an example?

A function is a block of statements that performs a specific task. Let's say you are writing a C program and you need to perform a same task in that program more than once. In such case you have two options: a) Use the same set of statements every time you want to perform the task.


2 Answers

How about a utility method instead:

public static class MyUtilities
{
    public static bool DoUpdate<T>(
        this T target, T source) where T: class
    {
        if(target == null) throw new ArgumentNullException("target");
        if(source == null) throw new ArgumentNullException("source");

        if(ReferenceEquals(target, source)) return false;
        var props = typeof(T).GetProperties(
            BindingFlags.Public | BindingFlags.Instance);
        bool result = false;
        foreach (var prop in props)
        {
            if (!prop.CanRead || !prop.CanWrite) continue;
            if (prop.GetIndexParameters().Length != 0) continue;

            object oldValue = prop.GetValue(target, null),
                   newValue = prop.GetValue(source, null);
            if (!object.Equals(oldValue, newValue))
            {
                prop.SetValue(target, newValue, null);
                result = true;
            }
        }
        return result;
    }
}

with example usage:

var a = new MyClass { Name = "abc", Age = 21 };
var b = new MyClass { Name = "abc", Age = 21 };
var c = new MyClass { Name = "def", Age = 21 };

Console.WriteLine(a.DoUpdate(b)); // false - the same
Console.WriteLine(a.DoUpdate(c)); // true - different

Console.WriteLine(a.Name); // "def" - updated
Console.WriteLine(a.Age);

Note that this could be optimized hugely if it is going to be used in a tight loop (etc), but doing so requires meta-programming knowledge.

like image 197
Marc Gravell Avatar answered Nov 01 '22 12:11

Marc Gravell


Your snippets should be under

C:\Users\CooLMinE\Documents\Visual Studio (version)\Code Snippets\Visual C#\My Code Snippets

The most easy way you be taking an existent snippet and modifying it to avoid reconstructing the layout of the file.

Here's a template you can work with:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>snippetTitle</Title>
            <Shortcut>snippetShortcutWhichYouWillUseInVS</Shortcut>
            <Description>descriptionOfTheSnippet</Description>
            <Author>yourname</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                </Literal>
                <Literal Editable="false">
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[yourcodegoeshere]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

This should come in handy when you want it to generate names based on the class name and so on: http://msdn.microsoft.com/en-us/library/ms242312.aspx

like image 45
coolmine Avatar answered Nov 01 '22 12:11

coolmine