Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, April 9, 2014

ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary — Speed, memory, and when to use each?


Array - represents an old-school memory array - kind of like a alias for a normal type[] array. Can enumerate. Can't grow automatically. I would assume very fast insertion and retriv. speed.

ArrayList - automatically growing array. Adds more overhead. Can enum., probably slower than a normal array but still pretty fast. These are used a lot in .NET

List - one of my favs - can be used with generics, so you can have a strongly typed array, e.g. List. Other than that, acts very much like ArrayList.

Hashtable - plain old hashtable. O(1) to O(n) worst case. Can enumerate the value and keys properties, and do key/val pairs.

Dictionary - same as above only strongly typed via generics, such as Dictionary

but note Hashtable has less performance than Dictionary because of Boxing and Unboxing.

SortedList - a sorted generic list. Slowed on insertion since it has to figure out where to put things. Can enum., probably the same on retrieval since it doesn't have to resort, but deletion will be slower than a plain old list.

I tend to use List and Dictionary all the time - once you start using them strongly typed with generics, its really hard to go back to the standard non-generic ones.

There are lots of other data structures too - there's KeyValuePair which you can use to do some interesting things, there's a SortedDictionary which can be useful as well.




Courtesy - Stackoverflow


Wednesday, March 26, 2014

Access modifiers

public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
private
The type or member can only be accessed by code in the same class or struct.
protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.
internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.
protected internal
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

Thursday, August 13, 2009

How To Create Dynamic TextBox With Event Handler

    protected void Page_Load(object sender, EventArgs e)
    {
        createTxt();
    }

    private void createTxt()
    {
       
        TextBox txt = new TextBox();
        txt.ID = "txt1";
        txt.AutoPostBack = true;
        txt.TextChanged += new EventHandler(txt_TextChanged);
        form1.Controls.Add(txt);       
    }

    void txt_TextChanged(object sender, EventArgs e)
    {
        TextBox txtBx = (TextBox)sender;
        Page.Title = txtBx.Text;
    }


Monday, August 10, 2009

How To Convert a string to TimeSpan

TimeSpan.Parse("00:00:00");

Wednesday, July 29, 2009

How To Change the start page Silverlight XAML

Go to app.xaml.cs, find Application_Startup, set your xaml page which you want to run during startup.

app.xaml.cs
private void Application_Startup(object sender, StartupEventArgs e)
{
// this.RootVisual = new Page(); // Default
this.RootVisual = new UserDefinedXaml(); // Changed Xaml, if u add UserDefinedXaml.xaml to your project.
}


app.xaml.vb
Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
Me.RootVisual = New UserDefinedXaml()
End Sub

Tuesday, July 28, 2009

How To Round Off The Decimal String

Math.Round(Convert.ToDouble("17.8"));

OutPut : 18


Thursday, July 23, 2009

What's the difference between Dataset.clone and Dataset.copy ?

    Clone :- It only copies structure, does not copy data.
    Copy  :- Copies both Structure and data

Boxing & UnBoxing

C# provides two types of variables they are Value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.

Example:

class Test
{
    static void Main() {
        int i = 1;
        object o = i;        // boxing
        int j = (int) o;     // unboxing
    }
}


Monday, July 20, 2009

whats the Difference between Page.RegisterClientScriptBlock and Page.RegisterStartupScript

The RegisterClientScriptBlock method inserts the client-side script immediately below the opening tag of the Page object's
element. Form elements at this stage are not instantiated, so the code cannot access the form elements.

The RegisterStartupScript method inserts the specified client-side script just before the closing tag of the Page object's
element. Form elements at this stage are instantiated, so the code can access the form elements.


Tuesday, July 14, 2009

Retrieve Content From Web Page - Screen Scraping

To retrieve the HTML code of a URL(this process is know as Screen Scraping), .NET provides WebClient class under System.Net namespace.Here I created a sample method which takes a URL and returns the HTML code.Include System.Net & System.Text namespaces

    private string GetPageContent(string url)
    {
             
string src = string.Empty;
             
try
             {
                     
WebClient client = new WebClient();
                     
UTF8Encoding encoding = new UTF8Encoding();
                      src = encoding.GetString(client.DownloadData(url));
              }
             
catch (Exception ex)
             {
                      Response.Write(ex.Message);
              }
              
return src;
      }


Close Window from CodeBehind

Page.RegisterStartupScript("CloseWin", "<script language='javascript'>{self.close();}</script>;");

Thursday, July 9, 2009

What is the difference between Convert.ToInt32 and Int32.Parse

if(STRING != null)
{
    Convert.ToInt32(string) AND Int32.Parse(string) Yield Identical Results;
}
else
{
     Int32.Parse(null) throws an ArgumentNullException;
     Convert.ToInt32(null) returns a zero;
}


How To Do Case Insensitive String Comparison

        if (System.String.Compare("xploredotnet", "XPlorEdotnet", true) == 0)
        {
            Response.Write("Equal");
        }
        else
        {
            Response.Write("!Equal");
        }


Wednesday, July 8, 2009

Whats The Difference Between string and stringbuilder

String

Strings are immutable and they are actually returning a modified copy of the string.

StringBuilder

Strings are mutable there object as a buffer that can contain a string with the ability to grow from zero characters to the buffer's current capacity. Until you exceed that capacity, the string is assembled in the buffer and no object is allocated or released. If the string becomes longer than the current capacity, the StringBuilder object transparently creates a larger buffer. The default buffer initially contains 16 characters

Thursday, June 25, 2009

How to convert string to int

        //Int32.TryParse Method (String, Int32%)
        // This method Converts the string representation of a number to its 32-bit signed integer equivalent,it return whether conversion succeeded or not
        int num;
        string[] value = { "123", "test", "-123" };
        for (int i = 0; i < value.Length - 1; i++)
        {
            bool result = Int32.TryParse(value[i].ToString(), out num);
            if (result)
            {
                Response.Write("String " + value[i].ToString() + " Converted Successfully");
            }
            else
            {
                if (value[i] == null) value[i] = "";
                Response.Write("Attempted For " + value[i] + " failed.");
            }
        }

Saturday, April 25, 2009

how to encrypted connection string in web.config

using System.Web.Security;

using System.Configuration;

using System.Web.Configuration;



Encrypt


Configuration Myconfig = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = Myconfig .GetSection("connectionStrings");
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
Myconfig .Save();
}


Decrypt


Configuration Myconfig = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = Myconfig .GetSection("connectionStrings");
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
Myconfig .Save();
}


Note
once the data is encrypted, when it's read from an ASP.NET page (i.e., reading the connection string
information from a SqlDataSource control or programmatically, via ConfigurationManager.ConnectionStrings[connStringName].ConnectionString),
ASP.NET automatically decrypts the connection string and returns the plain-text value.

Monday, April 20, 2009

how to make a page not to get cached

HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();

Friday, March 20, 2009

How To Convert ASCII Code To String

char.ConvertFromUtf32(34)




Monday, January 12, 2009

how to fix decimal places


Decimal.Round
method used to a specified number of decimal places.

decimal
.Round(99.2789m ,2).ToString();

Note

Without the suffix m, the number is treated as a double, thus generating a compiler error.

Output

99.28

Tuesday, January 6, 2009

How to convert strings to lower, upper, titlecase

string str = "xploReDOtneT wElcomeS yOU";

Response.Write("Orginal Text:- " + str + "
Lower :- " + str.ToLower() + "
" + "Upper :- " + str.ToUpper() + "
" + "Title Case :- " + System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str));



OUTPUT



Orginal Text:- xploReDOtneT wElcomeS yOU

Lower :- xploredotnet welcomes you

Upper :- XPLOREDOTNET WELCOMES YOU

Title Case :- Xploredotnet Welcomes You