Tuesday, July 22, 2008

Decide the Accessibility of Class Members in C Sharp

Another article in wikiHow ...


How to Decide the Accessibility of Class Members in C Sharp


from wikiHow - The How to Manual That You Can Edit

One of the choices you always make as a C# programmer is to decide the accessibility of each member (field, event, property and method) you declare in your classes. For advanced C# programmers, this is not actually really hard, but it can be pretty destructive for new to intermediate C# programmers, and seldom, even to advanced one. This article outlines the process of deciding the accessibility of your members in a systematic, easy to remember and straightforward approach.

Steps

  1. Design and implement your members as if you have already decided their accessibility level (usually this is done by implementing all members as public)
  2. Start deciding the accessibility of each member by itself repeating the following steps on all members:
    1. Start by giving the member the lowest accessibility possible: (private)
    2. Answer the following questions:
      • Will any existing code in your application or solution be affected by declaring the member on this accessibility level? For example, some other class might have code that accesses this member or uses it and because of the current level of accessibility chosen, it won't be able to access it anymore.
      • Is your member designed to be used by other developers, and if so, will they be able to access it in its current accessibility level?
      • In your future code, will changing the accessibility of this member be near impossible?
      • Is your class intended to be inherited, and if so, will the inheriting class face troubles accessing this member (if it is allowed to)?

    3. Check if the answers to all the previous questions were "no" or not.
    4. If the answers were all "no", leave the accessibility level as it is and start deciding the accessibility of another member
    5. If one or more of the answers was "yes", increase the level of accessibility one degree and repeat the steps for the same member, from step 2

Tips

  • Stick to this approach until you find that more than 90% of your decisions without using this approach match the results obtained by applying this approach, then you can start counting more on your own initial judgment.
  • When you become more and more familiar with programming in C#, many standard choices become obvious and they do not need a method to be decided. Hence, you start applying this approach only to those member you doubt or not included in any standard.
  • Even for advanced programmers, this approach can be helpful when used while skimming through your code in the final stages. It might catch some member declared using a higher accessibility than actually required even if that happened by chance or as a result of a typing error.
  • Some of the standard accessibility levels that became well established amongst C# programmers are:
    • Fields are usually declared private in structs and sealed classes and as protected in most other classes (unless you do not intend to inherit the class neither allow anyone who does to access the field, then private it is)
    • Class fields that are static readonly or const are usually public as they usually hold constant data available to other users of the class
    • Methods can be declared of any accessibility but usually are either:
      • private for internal implementation methods.
      • protected for virtual methods such as event firing methods.
      • public for user methods (methods that will be used by users of the class)

    • Events are usually public. In rare cases we need private events and even less protected events.
    • Properties are usually public or private. In rare situations we need protected or internal properties.

Warnings

  • It is considered a very bad programming practice to declare members with higher accessibility levels than they really require. This puts holes in your code.
  • Do not take the last tip in the "Tips" section as a starting point unless you are really familiar with the steps before it and have applied them many times. They are not always correct and they depend mainly on the situation.

Related wikiHows

Article provided by wikiHow, a collaborative writing project to build the world's largest, highest quality how-to manual. Please edit this article and find author credits at the original wikiHow article on How to Decide the Accessibility of Class Members in C Sharp. All content on wikiHow can be shared under a Creative Commons license.

Sunday, July 20, 2008

How to Use Regular Expression Classes in the .Net Framework

Programming Language: Any .NET Language
Type: Tutorial
Level: Everyone
Topic Category: General Programming
Main Series: Regular Expressions in the .NET Framework
Topic Title:
How to Use Regular Expression Classes in the .Net Framework
My last article on wikiHow:
How to Use Regular Expression Classes in the .Net Framework - wikiHow

Many beginning programmers spend much time coding search and replace logic while the .NET framework offers a powerful class framework to use regular expressions that you can use to perform various tasks on text and binary data. This article introduces you to the regular expression classes in the .NET framework and how to use them to perform tasks easier in a systematic way.

Steps
  1. Decide the specific use of regular expressions you need. Regular expressions are normally used for one of the following:
    1. Check if a string has a certain pattern within it
    2. Validate a string against a pattern
    3. Replace a specific pattern with another pattern
    4. Split a string using a pattern delimiter
    5. Find all ocurrences of a certain pattern within a string
    6. Extract pattern pieces/groups from a string (like in syntax checking/highlighting)
  2. Design and decide the regular expression you want to use. See a tutorial on regular expressions or visit an online library of regular expressions
  3. Decide the regular expressions matching options you want to use. The setting you need to decide are:
    1. Case sensitivity of matching
    2. Whether you want to ignore any white spaces within the regular expression while matching or not
    3. Whether the matching is multiline or not (this changes the meaning of ^ and $ to match to the beginning and end of lines and not only the beginning and end of the whole string)
    4. The direction of the matching process (left-to-right or right-to-left)
    5. Whether . will match any character including or not including new line
    6. Whether to compile the regular expression to the assembly (slow start up, fast processing) or not (the contrary)
    7. Whether to ignore culture variance/change or not
    8. Whether to use ECMA Script compliant mode or not
    9. Whether to capture every group (any sub-expression within parenthesis) or only groups that are named
  4. Create a RegexOptions object and add all options (by using bit-wise or "|") - This step is optional
  5. Choose the member method you want to use. This depends on your choice in step 1. You have the following choices:
    • IsMatch() - if you only need to check whether a match was found or not
    • Match() - if you want to get the first match found. Calling this method again will get the next match and so on.
    • Matches() - if you want to retrieve all matches of the pattern in one call
    • Split() - if you want to split the string at the matches of the pattern
    • Replace() - if you want to replace the matches of the pattern with another pattern or string
  6. Decide whether you want to use the static version of the method or the instance version. Static methods do not require the creation of a Regex object but they do not keep the status of matching between calls. According to your choice, follow the following steps:
    • For static versions of the methods:
      1. Declare an appropriate reference to hold the results of the operation if necessary. Here is a list of the methods and the type of results they return:
        • IsMatch() - bool
        • Match() - Match
        • Matches() - MatchCollection
        • Replace() - string
        • Split() - string[]
      2. Call the appropriate method from the Regex class passing it the regular expression, the string, the options, and the replacement pattern in case of Replace() and assign the result to the reference you declared in the previous step.
    • For instance versions of the methods:
      1. Create a Regex object passing the regular expression you created, and the matching options to the constructor.
      2. Declare an appropriate result reference to hold the results obtained (like step 1 in the static version of the method)
      3. Call the method you choose from the regex object passing it the string to be matched and assign the result to the reference created in the previous step.
  7. Use the results obtained at the end of step 6 in the rest of your code. Usual uses of results are listed below in the "Common Uses of Regex Methods Results" section
Common Uses of Regex Methods Results
  • IsMatch(): returns a boolean value that is usally used in:
    • A single conditional construct such as the "if .. else" code construct or the "?:" operator construct. This is usually when you want to check if a pattern generally exists in a string to decide whether to do some action or not (for example check if the text of a post contains some offensive word to decide whether to allow the post or ban it altogether)
    • A looping construct such as a while or do ... while loop. This usually is used with instance versions of the method Match to iterate through all matches as long as there are matches to iterate through. Sometimes, it is used with streamed string to check the matches of apattern in a text while it arrives through the stream.
    • Validation of controls. Usually this is done by binding some property of the control to the result (for example, making a textbox disabled as long as the regex can not find a match in the string within the text box
  • Replace(): returns a string with the pattern replaced with the replacement pattern or string. The resulting string is usually used in place of the original string. Some examples of the use of Replace() are:
    • Replacing all offensive words in a post with special characters such as ! or #
    • Replacing all html markup with html code that will display the markup instead of executing it (for example, replacing <>
    • Encrypting strings (premutation encryption)
    • Replacing special characters with other escaped values (for example replacing \ with \\)
  • Split(): returns a string array with all tokens after spliting the original string at the patterns found. This is usualy used in code parsing.
  • Match(): returns a Match object that has information on the match found by the last call of Match(). Match objects contain information on capture groups and captures within the single match. Example uses of the Match object result and the Match() method:
    • Syntax highlighting.
    • Storing the matches found in some data storage facility such as a database.
    • Performing more complex replacing on the string by calculating the replacement of each capture.
    • Detailed finding of matches within a long text.
  • Matches(): returns a MatchCollection object which is actually a collection of Match objects (you may think of it as a typed ArrayList of Match objects). This method is a call-once alternative to Match() so it has the same uses.
Tips
  • All matching options are turned off by default (that is, if you don't specify any of the options or use RegexOptions.None)
  • If you don't uinderstand any of the regular expressions matching options, leave turned off.
  • You can use Regex.Escape() and Regex.Unescape() methods to escape/un-escape special regex characters within a regular expression
  • To get the regular expression that was passed to the constructor of a Regex object, use the ToString() method. The method is overriden in Regex so that it returns the regular expression.
  • Thoroughly examine your regular expression before using it in a production-environment application. Regular expressions can be very tricky. Look at the "Related websites and online tutorials" section for further reading on regular expressions.
  • Use lookahead and lookbehind expressions wisely. They are hard to write and cost a lot of processing.
  • If your regular expression is large, uses a lot of backtracking, very complex or is intended to process large amounts of data, consider using a compiled assembly version of the regular expression. You can create regular expressions compiled assembly by using the Regex.CompileToAssembly() method.
Warnings
  • Passing an invalid regular expression to the constructor of Regex or to one of the static methods in the Regex class will through an exception so use try ... catch blocks.
  • Extra large regular expressions might cause the executing PC to run out of memory, so avoid using them.
Things You will Need
  • A .NET or mono compliant compiler and programming language.
  • A prior knowledge of regular expressions. See the "Related Websites and Online Tutorials" section for further information on regulare expressions.
  • A regular expressions toolbox application like RegexBuddy will help you test your regular expressions. This is optional.
  • A .NET integrated development environment will help you write code easier. This is optional.
Related Websites and Online Tutorials
Related wikiHows

Thursday, July 10, 2008

Create an Event for a C Sharp Class

Programming Language: C#
Type: Guide, Tutorial
Level: Moderate
Topic Category: General Programming
Topic Title:
Create an Event for a C Sharp Class - Article I wrote for wikiHow


I found this new Wiki which is also powered by WikiMedia, the same organization that powers Wikipedia. It features a wiki of how-to articles wrote by volunteers, and I can't resist this. So I wrote the following article in wikiHow. It was my first contribution to the site and I hope it will not be the last. I also include it here for those not familiar with wikiHow and for my students. I kept the same article structure used in wikiHow which is designed for good how-to documents and might be not really appropriate for a blog. however, because the site is based on a Creative Commons license, I had to keep the disclaimer at the end. My Screen Name on wikiHow is C#Freak which I'm trying to use in every community from now on.

from wikiHow - The How to Manual That You Can EditMany C# programmers use events in other classes by attaching event handlers to them but have you ever wanted to implement your own event(s) in classes that you develop? This is a systematic straightforward guide to creating your own events without worrying about forgetting anything.

Steps

1. Create the Event Arguments Class:

  1. Decide what you want to communicate with your event subscribers (other programmers who will attach event handlers to your event). For example, if your event is to notify developers when a value changes, you might want to tell them the old value and the new one. If you have nothing to communicate to subscribers, use the System.EventArgs class and skip this step.
  2. Create a class named EventNameEventArgs where EventName is the name of your event
  3. Inherit the EventNameEventArgs class from System.EventArgs
  4. Create a protected field for each piece of data you want to communicate with your subscribers. For example, in an event that will notify developers of a change in a string value, you might want to tell them the old and the new strings so the fields will look like:
    protected string oldVal, newVal;
  5. Create a public property for each field you created in 1.4 that has only a get{ return fieldName;} method (where fieldName is the name of the field you created in 1.4
  6. Create a private empty constructor for the class with no implementation. The constructor should look like: private EventNameEventArgs(){}
  7. Create a public constructor for the class that takes as many arguments as there is fields/data. For example, in a string value change event, the constructor will look like:public EventNameEventArgs(string oldValue, string newValue){oldVal = oldValue; newVal = newValue;}

2. Declare the event delegate. If you did not create an event arguments class because there is no data to communicate with subscribers, use the System.EventHandler delegate and skip this step. The delegate declaration should look like: public delegate void EventNameHandler(object sender, EventNameEventArgs e);

3. Declare the event itself in the containing class: use the event handler delegate you declared/decided in 2 as the event type. The declaration should look like:public event EventNameHandler EventName;

4. Declare the event-firing method - a protected virtual method that has exactly the following declaration:protected virtual void OnEventName(EventNameEventArgs e){ if(EventName != null) { EventName(this, e); } }Use the event arguments class you decided to use in 1

5. Call the event-firing method you declared in 4 whenever the event occurs. This is the hardest part. You should know when the event you are creating will fire (what areas in your code causes the event to occur) and call the method with the appropriate event arguments class instance. For example, in the string value change event, you must see what code can cause this value to change, save its old value before the change, allow the code to change the value, create an event arguments object with the old and new values passed to the constructor and pass the object to the event-firing method.

Tips

  • Be committed to the naming convention stated in this guide, it is a de-facto standard and most .NET/Mono developers use it.
  • Do not over communicate to your subscribers. In other words, do not transfer data that is not related to the event.
  • Choose the name of your event carefully and clearly. Event names like "ValPsd" instead of "ValuePassed" is not encouraged.
  • Usually, the accessibilities used in this article is the case. However, you can change the accessibility of any declaration as long as it does not render the element changed unusable by other elements of the event creation process.
  • Examine all places in your code where the event might occur. Sometimes, more than one piece of code causes the event to fire.
  • Watch for any changes you make to your class after you declare the event. See if the change affects the triggering/firing of the event.

Warnings

If you are adding the event to a struct instead of a class, take notice of the following changes:

  1. Use "private" instead of "protected virtual" when declaring the event-firing method in 4.
  2. In the constructor of the struct that declares the event, you must initialize the event itself or you will get a compile error. Initialize events by creating new event handler delegate objects and assigning them to the event. The initialization code should look like:EventName = new EventNameHandler(); or EventNameHandler = null;

Things You'll Need

  • A .NET framework installed (either MS .NET framework on Windows or Mono on other operating systems).
  • A C# compiler (the csc tool in the MS .NET SDK, cmcs in the Mono framework, or the compiler included in .NET IDEs such as Visual Studio 2005/2008 for Windows or MonoDev for Linux).
  • The code of the class you wish to add the event to.
  • Some code editing tool (Notepad is enough, but Visual Studio, MonoDev, Notepad++ or any other editor might make development and code writing easier.
Article provided by wikiHow, a collaborative writing project to build the world's largest, highest quality how-to manual. Please edit this article and find author credits at the original wikiHow article on How to Create an Event for a C Sharp Class. All content on wikiHow can be shared under a Creative Commons license.