IMPORTANT PLEASE READ!
Website development and design blog, tutorials and inspiration

C# Class and Method Attributes Explained

How Method Attributes are used

By , Written on in C#

C# Class and Method Attributes Explained

768 words, estimated reading time 4 minutes.

Method Attributes provide a means of changing the behaviour of a method or class. You can setup conditional flags, mark a method as a web method, obsolete or allow a class to be serialized to XML.
 
C# Programming Series
  1. Introduction to Programming
  2. What is C#?
  3. Your First Console Application in C#
  4. Introducing Methods and the Main() Function in C#
  5. Introducing C# Classes and Structs
  6. C# Data Types, Variables and Casting
  7. C# Program Flow Control and Entry Points
  8. Passing Parameters to Methods and Return Values in C#
  9. C# Access Modifiers and Scope
  10. C# Interfaces and Classes
  11. Using Namespaces in C#
  12. C# Conditional Statements
  13. Looping and Iteration in C#
  14. Using Arrays and Lists in C#
  15. C# Constants and Read-Only Variables
  16. Error and Exception Handling in C#
  17. Using Recursion in C#
  18. C# Operator List
  19. Class Inheritance in C#
  20. C# Class and Method Attributes Explained
  21. C# Class Constructors and Destructors
  22. C# Generics Variables
  23. XML Serialization and Deserialization
  24. C# String Formatting Examples

Attributes are specified in square brackets before the class or methods that they are to apply to.

  1. [WebMethod]
  2. public string getPageTitle
  3. {
  4. return "Test Code";
  5. }

WebMethod and WebService

Let's first look at web method, as it was used in the above example. In Web Services, all methods are all hidden from direct access to the Internet. You need to specify, using the WebMethod attribute, any method you want to expose to the Internet.

  1. public string HelloWorld()
  2. {
  3. return "Hello World";
  4. }
  5.  
  6. [WebMethod]
  7. public string web_HelloWorld()
  8. {
  9. return "Hello World";
  10. }

In the above example, anybody connecting to the web service will only be able to invoke the web_HelloWorld method even though the regular HelloWorld is marked as public.

You must also mark the class as a web service using the WebService attribute. This attribute accepts parameters in the form of a namespace.

  1. [WebService(Namespace="http://tempuri.org/")]
  2. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  3. public class Service : System.Web.Services.WebService
  4. { ...

In the above example you can see how to apply more than one attribute to a class.

Serializable

When you mark an object as [Serializable] you are informing the compiler that at some point you want to save the object as XML data stream. You can also implement the ISerializable interface.

To serialise an object you can use an XML Serializer and StreamWriter to write to a file.

  1. using System;
  2. using System.Xml.Serialization;
  3. using System.IO;
  4.  
  5. [Serializable]
  6. public class myTestClass
  7. {
  8. public string myString = "Hello World";
  9. public int myInt = 1234;
  10. public string[] myArray = new string[4];
  11.  
  12. public string myMethod()
  13. {
  14. return "Hello World";
  15. }
  16. }
  17.  
  18. class Program
  19. {
  20. static void Main()
  21. {
  22. myTestClass test = new myTestClass();
  23. test.myArray[0] = "qwerty";
  24. test.myArray[1] = "asdfgh";
  25. test.myArray[2] = "zxcvbn";
  26. test.myArray[3] = "123456";
  27.  
  28. XmlSerializer mySerializer = new XmlSerializer(typeof(myTestClass));
  29. StreamWriter myWriter = new StreamWriter("c:/mtTestClass.xml");
  30. mySerializer.Serialize(myWriter, test);
  31. myWriter.Close();
  32. }
  33. }

When run, this will create an XML document containing the current data of the object.

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <myTestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  3. <myString>Hello World</myString>
  4. <myInt>1234</myInt>
  5. <myArray>
  6. <string>qwerty</string>
  7. <string>asdfgh</string>
  8. <string>zxcvbn</string>
  9. <string>123456</string>
  10. </myArray>
  11. </myTestClass>

Deserialize Objects

Deserialization is the opposite of serialization, reading the data from XML and converting it into an object. The process is very similar to the serialization method above.

  1. static void Main()
  2. {
  3. myTestClass test;
  4.  
  5. XmlSerializer mySerializer = new XmlSerializer(typeof(myTestClass));
  6. FileStream myFileStream = new FileStream("c:/mtTestClass.xml",FileMode.Open);
  7.  
  8. test = (myTestClass)mySerializer.Deserialize(myFileStream);
  9.  
  10. // Just to prove it works
  11. Console.WriteLine(test.myArray[0]);
  12. }

Conditional

The conditional attribute can be set on methods so that they can be called only if that condition is true. An example of this is a debug log. When the program is compiled for a debug build, the method will run each time it is called, however when compiled for release the method will never be called. The method is still compiled into the assembly regardless of the target build.

  1. class Program
  2. {
  3. [Conditional("DEBUG")]
  4. static void debugMethod(string message)
  5. {
  6. Console.WriteLine(message);
  7. }
  8.  
  9. static void Main()
  10. {
  11. Console.WriteLine("This is a test");
  12. debugMethod("This is debug message");
  13. Console.WriteLine("This is a test");
  14. }
  15. }

When the program is compiled for debug the console window will show:

This is a test
This is a debug message
This is a test

When run, for a release build the console window will show:

This is a test
This is a test

Obsolete

The obsolete attribute is used to mark a method that should not be used any more. It allows for backward compatibility when using assemblies.

  1. [Obsolete("This class is obsolete, please use testClass instead.")]
  2. class oldTestClass
  3. {
  4. public string Hello()
  5. {
  6. return "Hello";
  7. }
  8. }
  9.  
  10. class testClass
  11. {
  12. public string Hello()
  13. {
  14. return "Hello World";
  15. }
  16. }
  17.  
  18. class Program
  19. {
  20. static void Main()
  21. {
  22. oldTestClass test = new oldTestClass();
  23. test.Hello();
  24. }
  25. }

This will display a warning message at compile time with the obsolete message. It will not stop any other code from using the method, or break any existing code; it will only show the message to developers.

More Attributes

There are many more attributes, you can find them all by inputting a [ and invoking IntelliSense to see a list.

Last updated on: Friday 23rd June 2017

Did you Like this Post? Why not Like us on Facebook?

 

Comments
  1. Krishna
    Krishna

    Very nice tutorial...

    Everyone must go through dis... its really good...

    Thanks & Regards,
    Krishna

Leave a Reply

Your email address will not be published.