C#

94K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

This article is for Object-Oriented Programming (OOP) beginners.

An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Interface member. In C# multiple inheritance is achieved with the help of Interfaces.

Therefore, if the Development Team is large or 3rd-party vendors are involved, then it may possible that two team members may end up creating two different Interfaces with the same method name. Consequently, as a developer you may have to implement both these Interfaces in one Class.

Scenario: So let’s assume that –

You have two different Interfaces let’s say ICustomer and IVendor. Both the Interfaces have a method with same name let's say GetData().

GetData() from ICustomer would return the list of customer names while GetData() from IVendor would return the list of vendor names. In the data access layer, a single class CompanyDAL implements both these Interfaces.

See attached Code Snippet for Interface definitions –
using System.Collections.Generic;

namespace ExplicitInterfacesSite
{
    // Simple interface for Vendor class
    public interface IVendor
    {
        // Return the list of vendor names
        List<string> GetData();
    }

    // Simple interface for customer class
    public interface ICustomer
    {
        // Return the list of  customer names.
        // This function name is conflicting with 

Open in new window

3
Introduction
Hi all and welcome to my first article on Experts Exchange.
A while ago, someone asked me if i could do some tutorials on object oriented programming.

I decided to do them on C#. Now you may ask me, why's that?
Well, one of the reasons was that i have more C# than C/C++ knowledge.
Another one is that C# is becoming more and more a very important language, and forces you to think object oriented, wich is a style of programming were lots of people who are used to traditional techniques have trouble understanding with.
And last but not least, when you combine C# with the powerfull Microsoft XNA Framework it becomes fairly easy to create games that work on both PC and Xbox and even on Windows Phone 7.

Also, i decided to write them, instead of making video's.
Video's are handy, but not that functional when it comes to programming (imo). When you want to explore something in between, you have to pause them, remember where you were, you need audio so not development in the middle of the night with your wife sleeping next to you and lots of other downsides.
Also my English pronouncing is far from perfect.
Maybe i will make a video sometime when i really want to show something special, but changes are low.

I'm not a fulltime software developer as i'm also responsible for a part of the network management in the company where i work, but i'll try to do my best to make things as clear as possible for you all.
If someone finds an error in my ways of …
1

Expert Comment

by:krg2
Excellent work, Japy!

I truly appreciate your tutorial, it is very helpful and provides a good reference
0
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can be easily solved by simply using a graphics creation tool such as Paint, Gimp, or Adobe Photoshop and the Transparency key tool found within the C# program.

To ensure you have the correct amount of space for all form objects needed and even room for adding features down the road, design of your new program becomes the key to a successful build. In keeping with that tradition of design we will need to first layout how we would like our form to look at the end of our project.

For this example we will be creating a mock MP3 Player. I have decided to make the form appear in the shape of a banner with the display information and buttons in the center. Here is how I would like my form to look when it is complete:

 image001.jpg

As you can tell I am not an artist but for the purpose of this article let’s pretend it is the greatest design ever. You can do this step with nothing but a scratch piece of paper and pen just so you have a visual goal to work towards. Next we want to conceptualize a layout on the form to see if it meets your needs.

image002.jpg

Once again, despite the artistry it appears to be in line with my concept.

The next step is where we turn idea into reality. From here going forward…
3
This article introduced a TextBox that supports transparent background.

 TCTextBox demo

Introduction


TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the urge for it. TextBox is among one of them, but unfortunately, once in a while people want it to be transparent (such as this typical question in EE: Transparent TextBox in C#).

If you search on the internet for a solution, you will come across advices like subclassing TextBox and add the support to transparent background color, or, drawing your own background in the OnPaint event. It is rational theoretically but unfeasible practically, as revealed in the following analysis.

(For those who like fast food, you can skip the literature sections and jump to the “Using the Code” section to grab and eat. Actually I also get my hands wet immediately after a short hunting with no luck. After a couple of days working, when I decide to present this home-made component to public, I have to head back to the anatomization part to make the article complete. It costs me much more time than doing the simply coding stuff along.)

The traditional TextBox just refused to be tweaked


To verify the above common suggestions, I build a phantom class TestTextBox derived from TextBox. Again, test cases are flagged in the source code for users who like to practise by themselves.

Set background color as Color.transparent (Test Case 1)
1
LVL 8

Author Comment

by:trestan
systan, would you mind post the link where you see the same TXTextBox? Did you compare the source code bwtween the two?

It's also normal that not only one person think about the needs and create something similar:)
0
LVL 8

Expert Comment

by:mac-will
You aren't Disposing your 'SolidBrush' object.

You should wrap the new solidbrush in a using.
0

Summary:

Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to-use code snippet using BinaryFormatter with simple encryption is provided.


Introduction:

I was amazed the first time I read the dotnet documentation about serialization. Prior to the dotnet era, it was a big headache to deal with configuration data. You would have to write large code pieces to stream the data out to a file and then parse the long strings again to find out the proper data to read back. When playing with serialization, I was hoping to create a complete cache of the application and restore it just like nowadays Windows system “Hibernation” feature. Although the reality is always far from the imagination, dotnet serialization is still very useful in caching “part” of an application – the data objects.

Dotnet framework provides two types of serialization: shallow serialization, and deep serialization, represented by
   XmlSerializer in System.Xml.Serialization namespace and
   BinaryFormatter in System.Runtime.Serialization.Formatters.Binary namespace,
respectively. The differences between the two types are obvious: the former is designed to save and load objects in human-readable XML format, and the latter provides compact binary encoding either for…
4
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods.
Demo
Introduction

In one of my applications I needed a control that could be resizable at run time. Just like the canvas in MSPaint, you can resize it inside the host window. After a quick search on the internet I noticed that most solutions treating this simple issue as a beast.  An example of a "complex implementation" is in the EE Solution, here.

Using SendMessage is an intuitive temptation.  We could try the technique I descried in my previous article on how to drag a form -- wehe we simply flood mouse movement to the caption of the host form.  However, the parameters for resizing message scattered to eight directions and you'd have to calculate the delta in each direction to make it work.  That’s why the code tends to become so bulky.


Using PictureBox as decoration

When a control is runtime resizable, you'll certainly want to provide some visual indication to users. You can manually draw an “edge” on the control using graphic functions, and manually change the cursor type when the …
0

Expert Comment

by:Asus314
can you please share source code of your soft TcPaint ?
Thank you
0

Introduction

Although it is an old technology, serial ports are still being used by many hardware manufacturers.

If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to work on many clinical instruments as a job requirement to parse, extract patient test results and send them to a database backend for reporting. This means there are many serial ports attached to the computer.  I developed different C# applications for each instrument. However, whenever I needed to make any changes, I had to open source code of the application, compile and deploy over and over again. It was very time consuming and a headache.

This is why I developed a serial port programming language:  To reduce development time.  I have made the tool available as project on SourceForge.  In this article, I'll discuss some of its features and give you an idea of how to use it.


Application Features

It is a handy, simple application specially designed to simplify the development of RS232 based applications. It makes it easy not only to communicate with the serial port but also data parsing and extraction.

It requires .NET Framework 3.5 or above and supports all major Windows platforms including Windows XP, Windows Vista and Windows 7.

Key Features

Able to log multiple serial ports at the same time. The data logger has the capability to log multiple ports simultaneously so that
3
LVL 50

Expert Comment

by:DanRollins
This looks like an excellent tool.  You got my YES vote, above!

One of the very first projects I worked on (back in about 1980), was an interpretive language for use in controlling a modem during the log-in process when connecting to remote host systems (such as CompuServe).  It is VERY useful to be able to just tweak a script and retry -- much better than re-coding!
0
LVL 4

Author Comment

by:albay
I got the first YES vote from you. That is great.

Yes, I hate re-compile big projects over and over again.That is why I developed this application.
by the way I will appreciate, if you can change the link.

Thank you again.
0
Introduction

This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would get that off the bat and you are one of them you should understand by the end of the Part 1.  Part 2 will deal with creating objects and inheriting from IDisposable.

With wonderful things like disposable objects and garbage collection I feel most of our developer colleagues have forgotten about memory management and memory leaks. If you are one of those people who would say: “There is so much memory available these days we don’t need to worry about memory”, then you fall into 1 of 2 categories.

You have not developed anything more complex than a “hello world” app
You are a VB developer
Either way you don’t need to continue reading. (This article is meant for developers) ?

Before getting into the article consider the following priorities when developing:
Code must execute as fast as possible (yes I mean shaving off 1/(1 000 000) of a millisecond)
The application must be as small as possible (no useless processor executions)

How to use an object of type IDisposable

Let’s assume that you want to open a connection to Sql Server. There are 2 ways to do this with executing the .Dispose() method. By the way – you have to …
2
LVL 76
You are a VB developer
Not sure why VB developers are being singled out here. IDisposable is a .NET concept, not a C# or VB concept. It exists in both languages (even C++.NET and F# have it), and its intent is the same. Speaking of which...

...you have to call .Dispose() on a disposable object to free it from memory.
The intent of Dispose is not to release the object being disposed from memory. Its intent is for the programmer to trigger the object to release any unmanaged resources that the object may be holding on to. IDisposable has no bearing over when the object itself will be purged from memory by the GC. The GC itself has no knowledge of unmanaged resources, which is why Dispose exists. Dispose is for the programmer to explicitly trigger the release of unmanaged resources; Finalize (what you referred to as a "destructor") is an implicit trigger of the same.

With regard to using statements, there are actually times when a using is counter-productive--though, most times it is advisable to use a using.
0
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any questions.

WCF can not be directly called by VB6; we need to create a .NET bridge for it.  Below is how to create that bridge.

Create a .NET Class Library project

1. What all functionality are intended to be used in COM, create an interface for it.  The interface should be public and with the [ComVisible(true)] attribute.  If WCF is to be called, then this interface will be same as the contract interface in WCF (except attributes OperationContract and ServiceContract will not be added in .NETBridge interface.)
2. Create .NET class implementing this interface. (Here write all functionality i.e. logic, call service, hit db …)
3. Class should be public and should have following attributes
   a. [ClassInterface(ClassInterfaceType.None)]
   b. [Guid("<A GUID>")]
   c. [ComVisible(true)]
4. In Visual Studio, right click the project node in Solution Explorer.  Go to Properties -> Signing
5. Check Sign the assembly. Create a new key (using the dropdown control).
6. Build your application.
7. Open Visual Studio command prompt.
8. Use regasm /tlb:<urDesiredTLB>.tlb  <urDLL>.dll   i.e.
      regasm /tlb: wcfCaller.tlb wcfCaller.dll
1
In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions.
Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column.

First solution, the easy way
The first solution is to make the column slim enough, so that the record selectors are not drawn: the are on the left side of the column. Set the property RowHeaderWidth to a value less than 20, but this value depends on the style you used...

Second solution, the long way
OK, you can always redraw your items completely, by doing the work "by hand"...
This is what I found by Googling; it is in C# language, but I think it's easy to understand.

 void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs  e)

        {

            if (e.ColumnIndex == -1 && e.RowIndex > -1)

            {

                e.PaintBackground(e.CellBounds,true);

                using (SolidBrush br = new SolidBrush(Color.Black))

                {

                    StringFormat sf = new StringFormat();

                    sf.Alignment = StringAlignment.Center;

                    sf.LineAlignment = StringAlignment.Center;

                    e.Graphics.DrawString(e.RowIndex.ToString(),

                        e.CellStyle.Font, br, e.CellBounds, sf);

                }

                e.Handled = true;

            }

        }

Open in new window


Third solution, the smart way

I prefer this solution. I don't know if anyone (and it is probable) have already posted something similar, in this case I apologize :-)
This solution is the middle-way of the others. It is simplier and doesn't need to draw anything: just ask the datagridview to do the job for you.


Open in new window

0
C# And Nullable Types

Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a database column for instance) and assigning a value will change the result.
Nullable type is applicable to primitive (known as value) types where data is stored in the stack and .NET Framework implicitly initializes them to their default values, even though the developer did not do that. Applying Nullable type to primitive types helps going round discomfort of looking for equivalent decisions like creating:

A boxed value type. This is not strongly-typed at compile-time, and involves doing a heap allocation for every type.
A class wrapper for the value type. This is strongly-typed, but still involves a heap allocation, and the you have to write the wrapper.
A struct wrapper that supports the concept of nullability. This is a good solution, but you have to write it yourself.

Nullable types can be declared in two ways:
System.Nullable<T> variable
T? variable

Open in new window

T is the underlying type of the variable. It can be a struct but cannot be reference type.

Any value type may be used as the basis for a nullable type. For example:

int? i = 10;
double? d1 = 3.14;
bool? flag = null;
char? letter = 'a';
int?[] arr = new int?[10];

Open in new window

Each instance of the above inherits two public read-only properties from Nullable type:
HasValue – bool type stating that variable contains a value
Value
0
LVL 76
You might want to make a note about what "boxing" is. I have a feeling that people who do not know about Nullable may also not know what the concept of "boxing" is  :)
0
LVL 22

Author Comment

by:Ivo Stoykov
In brief:
(un)boxing = conversion.
value -> reference type = boxing (wraps value in a Object)
reference -> value type = unboxing (extracts value from a Object)

Here's what Microsoft says about boxing 8-)
0
Extention Methods in C# 3.0

by Ivo Stoykov

C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance.

These are static methods invoked as instance method. This allows developers to add functionality without necessity to create derived types, re-compiling or other modifications of existing objects. Also to extend sealed objects and avoiding deep digging into object inheritance tree.

Declaration

There are few "must do" in extension method declaration

1. Must be declared into static class
2. Method must be static
3. 1st parameter must be this.

This first parameter in method declaration is the most important one. It specifies witch type the method operates on. The keyword this defines that method is applied on the instance of defined type.

In the sample below we have only one parameter compound by three parts. Part one is the keyword stating that the method WordCount is applicable to String type.

Part two is the type itself -- String in our sample.

Part three is the particular instance of the type the method will be executed -- in the sample this is property name s. In other words the method will be applicable to any String instance.

In the sample we define in Main method a variable of String type named str. In the next row we use standard notation -- type, dot, method, parameters -- str type on the left of the dot becomes out first parameter in WordCount
0
Introduction
                                               
Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.
 
Also called: Implicitly typed local variables
 
The var keyword – in VB
 
I have heard many an argument about this new addition to the C# language. One of the main debates being: It’s so VB like, It reminds me of Dim.  So this is all I am going to say about its use in VB (and only because I think if VB programmers use it may make their code just a little better).
 
Its use in VB is slightly different to that in C#.  This is because VB has always had an unknown type keyword (dim), so you have to explicitly “turn on” the functionality by using the “Option Infer On” at the top of your module.  So to finish off for VB: To use this functionality turn it on and the declare your Variable like so:
 
   Dim MyStringVariable = "hello world"
 
When hovering the mouse over MyStringVariable you will notice the tooltip text says Dim MyStringVariable As String.  So you will not be able to do your usual VB thing and change its type later on to an int!
 
The var keyword
 
First of all to ease all your minds the var keyword is not evil VB code creeping into your C# IDE!  It is strongly typed (which means that you cannot put a string into it and then later on change its type to an int).
 
It must not be …
7
LVL 40

Expert Comment

by:it_saige
Agreed on all points.

But in reality, do you have to *know* what the result of using default on a type is?  Can you just not check for type to default(type) equality [or inequality] by using:
SomeType == default(SomeType)

Open in new window

As you have attested, the list is not exhaustive and, for the most part, is intuitive.

Can I blame my last example on poor coffee intake?  ;)

-saige-
0
LVL 76
Contrived example, but:

int x = 10;
int y = default(int);

double z = x / y;

Open in new window


I agree, it's mostly intuitive:  number types are all zero, and reference types are null.
0
Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Their role in programming, however, is still prominent, and likely will be for quite some time.

First of all, what are bit flags? A 'set' of flags is just a binary value, usually 8, 16, 32 or 64 bits long. They are usually expressed via enumerations, though I have seen cases where they are done strictly via hard-coded numeric values (which I don't advise doing). 32 bits is the default for .NET enumerations. Obviously, everything we do is technically binary--numbers, letters, strings, everything, so a set of flags is no different than your average integer. The differences lies in how we visualize the integer, and how we treat it. The difference is in the intent, not in the actual implementation of details of the objects. Anything in the computer world is binary, and anything that is binary can be visualized by us, either into 0's and 1's, or a base-10 number (which is any number you usually encounter, such as 23, 45, 50, or what have you).

As you know, every value in any programming languages can be expressed in binary. The whole "0100101" thing we do is not actually binary--it's just how we, as humans, visualize binary. I'll be using that visualization …
1
Anonymous Types in C#
by Ivo Stoykov

Anonymous Types are useful when  we do not need to follow usual work-flow -- creating object of some type, assign some read-only values and then doing something with them. Instead we can encapsulate this read only data into an anonymous type without first defining object explicitly. (Anonymous simply means "without a name".)

Anonymous types are class types that consist of one or more public read-only properties.

In C# 3.0 compiler generates anonymous types through object initializer, who cares to use appropriate types assigning given values to one or more fields or properties of an object. This is why anonymous types are not available in source code level.
Objects declared as anonymous types use the var keyword in place of the type name. Dislike JavaScript the var keyword here always generates a strongly typed variable reference.

Sample:
var v = new { Amount = 108, Message = "Hello" };

Open in new window


Note that there is no name for the class. Therefore, in declaration, we cannot specify type in front of the variable. Instead the var keyword is used.

var tells the compiler that we leave to it to infer the type of the variable for us. The var keyword can be used to reference any type in C#. So following declaration
var name = "Scott";

Open in new window

is identical with
String name = "Scott";

Open in new window


Because the var keyword produces a strongly-typed variable …
2
I was recently working on a project that uses a list view control. I had to dynamically add items based on a configuration file so I could not set the height of the list view at design time unless I wanted scroll bars. For my application, I wasn't expecting a large amount of items. Therefore, I wanted to always size the list view to just the right amount so that it would not show a vertical scroll bar. Unfortunately, there is no autosize property of the list view control. I was able to write a series of extension methods that let you auto size the list view control. This could be done by inheriting from the list view control instead. I chose the extension method model for this article so that you don't have to add a control to your tool box.

For maximum control, I separated the height and width functionality and then included an all encompassing method that calls both. For added flexibility, I allow you to set the number of items you want to display. To autosize it fully, pass in the number of items that the list view control contains.


1. Create the Extension Method Framework


using System;
using System.Windows.Forms;
namespace ListViewExtensionMethods
{
   public static class ListViewExtensions
   {
      public static void AutoSizeControlHeight ( this ListView lv, int maxItemsToShow, bool adjustForHorizontalScrollBar)
      {
      }
      public static void AutoSizeControlWidth ( this ListView lv, bool adjustForVerticalScrollBar )
      {
     

Open in new window

1
LVL 96

Expert Comment

by:Bob Learned
For owner-drawn ListView controls this code makes sense, but for details view with fixed-height items,  you should be able to use get the first item height, and calculate this way:

var itemHeight = listView.Items.OfType<ListViewItem>().First().Bounds.Height;
listView.Height = (itemCount + 1) * itemHeight + 6;

Open in new window


The only caveat is that the column header height is slightly taller than the other items.  You might be able to determine this, but for now I just added a fixed offset of 6 pixels.
0
Downloads

The associated files can be downloaded from the following links:

   Download Demo Project (39.18 KB)    * Warning, externally hosted.
   Download Source (8.2 KB)                     * Warning, externally hosted.

Introduction

This article presents an extension of the .NET ComboBox which provides custom drop-downs. The control can automatically add a resizer grip at the bottom of a drop-down.
Screenshot Examples
Design

Custom drop-down functionality can be achieved using the .NET ToolStripDropDown and ToolStripControlHost classes. These two classes are great because they prevent application forms from becoming inactive during drop-down. The custom popup functionality required by this control has been encapsulated within the class PopupControl (a new addition since the original article posting).

In addition to facilitating this control, the PopupControl class can be used to provide drop-down support in your own controls. The PopupControl also integrates the drop-down resize support (now without the need for a nested resizable container, see below for details).

Previously the drop-down control was resizable by nesting a resizable container. This was an okay solution (because it worked) but it caused some redraw errors during resize …
1

C#

94K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).