static int in c# - c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace LearnThread
{
class Delay
{
public int timePass()
{
static int i=0;
for(i=0; i<100;i++)
{
Thread.Sleep(1000);
}
return i;
}
}
}
Error:The modifier 'static' is not valid for this item
Why static is error here? We cannot use static for int as we can use in C language?

You can't declare a locally scoped variable as static, which is what you are doing.
You can create a static field or static property for a class (i.e. it is a member of a class), which would reside outside of a method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace LearnThread
{
class Delay
{
static int i=0;
public int timePass()
{
for(i=0; i<100;i++)
{
Thread.Sleep(1000);
}
return i;
}
}
}
Though, this code seems kinda dumb... why bother using a static field in a for-loop iteration? It can cause a lot of issues with multiple calls to the method. I presume that you're either learning C# by playing around with crazy code, or you are trying to solve another problem and threw this code in. Either that or.... you're doing it wrong. :)

You can not define static variable inside the function, only on class level.

You cannot have a static variable inside a method since it would go out of scope when returning from the method body. Move it to the class level and static ints are fully available.

Static Variable:A field declared with the static modifier is called a
static variable. A static variable comes into existence before
execution of the static constructor.
To access a static variable, you must "qualify" where you want to use
it. Qualifying a member means you must specify its class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace LearnThread
{
class Delay
{
static int i=0;
public int timePass()
{
for(i=0; i<100;i++)
{
Thread.Sleep(1000);
}
return i;
}
}
}

Related

How to do change the value in the class with the help of method in C#

I want to call an object from a different class and change its properties.
I want to get into this object and make changes.
But when I type the dot, the properties do not open.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
SINIF3 sınıf3 = new SINIF3();
//I want to get into this object and make changes.
//But when I type the dot, the properties do not open.
//For example
//sınıf3.gonder(1).number=2;
Console.ReadKey();
}
}
class DEGER
{
public int number = 1;
}
class SINIF3
{
public object gonder(int a)
{
DEGER objem = new DEGER();
DEGER objem2 = new DEGER();
if (a == 1)
return objem;
else return objem2;
}
}
}
Change the return type of the gonder method from object to DEGER. Of course you're not assigning the result of the gonder method to a variable, so the new object which you change the number field in will be thrown away.
Change the the method.
from public object gonder(int a)
to public DEGER gonder(int a)
otherwise you need to cast the object
something like
sınıf3.((DEGER )gonder(1)).number=2;
But you should try not to return object if you can.

Why I have to write the namespace to access to this extension method?

I have a project that has class to implement extension methods for some type. For example I have this class for ObservableCollection:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
namespace MyProject.Collections.Utils
{
public static class ObservableCollection
{
public static void RemoveAll<T>(this ObservableCollection<T> collection, Func<T, bool> condition)
{
for (int i = collection.Count - 1; i >= 0; i--)
{
if (condition(collection[i]))
{
collection.RemoveAt(i);
}
}
}//RemoveAll
}
}
With this class, in my main project I can use this library with the using:
using MyProject.Collections.Utils
And when I want to use the extension methods I can do:
ObservableCollection<MyType> myOC = new ObservableCollection<MyType>();
myOC.RemoveAll(x=>x.MyProperty == "123");
So I have access to my extension method.
However, I have another class for Decimal, is this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyProject.Decimal.Utils
{
public static class Decimal
{
public static decimal? Parse(this string paramString)
{
try
{
myCode
}
catch
{
throw;
}
}//Parse
}
}
But in this case, although in my main prject I import the class:
using MyProject.Decimal.Utils;
If I do this:
decimal? myDecimalParsed= Decimal.Utils.Decimal.Parse("123");
Why in this case I can't do this?:
decimal? myDecimalParsed= decimal.Parse("123");
thank so much.
Two problems:
You can't use extension methods as if they were static methods of the extended type
System.Decimal already has a Parse method, and the compiler always looks for "real" methods before extension methods.
In fact, you can write
decimal? miTiempoEstimadoParseado = decimal.Parse("123");
... but that will just call the normal method and then convert the decimal to decimal? implicitly in the normal way.
Note that you're not really using your method as an extension method at the moment anyway - to do so you'd write something like:
decimal? miTiempoEstimadoParseado = "123".Parse();
... but personally I'd view that as pretty ugly, partly as the method name doesn't indicate the target type at all, and partly because by convention Parse methods throw an exception instead of returning a null value on failure. You probably want to come up with a different name.

initializecomponent() don't exist in current context while using generics in c# web application

I am trying to create a generics in c# web application and using silverlight-5. This i have already implemented in c# console application.
I am trying to do same in webdevelopment using asp.net,c# and silverlight (and GUI using xaml) in Vs-2010. Whose GUI is displayed on internet explorer on running the code (by button click events).
In console application i do so by following code : (The code is to read a binary file as sole argument on console application and read the symbol in that file, These symbol could be int32/int16/int64/UInt32 etc.). So have to make this Symbol variable as "generic"(<T>). And in console application this code works fine.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace check
{
LINE:1 public class Huffman < T > where T: struct,IComparable < T >,IEquatable < T >
{
public int data_size, length, i, is_there;
public class Node
{
public Node next;
line:2 public T symbol; // This symbol is of generic type.
public int freq;
}
public Node front, rear;
LINE:3 public Huffman(string[] args, Func < byte[], int, T > converter)
{
front = null;
rear = null;
int size = Marshal.SizeOf(typeof (T));
using(var stream = new BinaryReader(System.IO.File.OpenRead(args[0])))
{
long length = stream.BaseStream.Length;
for (long position = 0; position + size < length; position += size)
{
byte[] bytes = stream.ReadBytes(size);
LINE:4 T processingValue = converter(bytes, 0); //**Here I read that symbol and store in processing value which is of type <T>**
//Then further i use this processingValue and "next" varible(which is on Node type)
}
}
}
}
public class MyClass
{
public static void Main(string[] args)
{
line:5 Huffman < long > ObjSym = new Huffman < long > (args, BitConverter.ToInt64);
// It could be "ToInt32"/"ToInt16"/"UInt16"/"UInt32"/"UInt64" with respective
//change in <int>/<short> etc.
//Then i further use this ObjSym object to call function(Like Print_tree() here and there are many more function calls)
ObjSym.Print_tree(ObjSym.front);
}
}
}
The same thing i have to achieve in C# silverlight(web application) with a difference that i have already uploaded and stored the file by button click (By Browsing it)(whereas i was uploading/reading file as sole argument in console application), This file upload part i have already done.
The problem now is how to make this "symbol" variable generic(<T>) here because i am not able to see any Object creation (In main(string[] args) method) where i could pass parameter BitConverter.ToInt32/64/16 (as i am doing in console application, please see code).
NOTE: please see that i have used in LINE 1,2,3,4,5 in my code (so that the same(or different if you have other approach) has to be achieved in the code below to make "symbol" of type )
Because in c# i get body of code like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace check
{
public partial class MainPage : UserControl
{
public class Node
{
public Node next;
public long symbol; // This symbol is of generic type.
public int freq;
}
public Node front, rear;
public MainPage()
{
InitializeComponent();
}
}
}
Could some one please help me in changing the code of this web application exactly similar to that console application code (I mean making "Symbol variable as generic(<T>)")
EDIT: When i do this:
(1) public partial class MainPage <T> : UserControl, IComparable < T > where T: struct,IEquatable < T >
(2) public T symbol; (In Node class)
(3) And all the buttons and boxes i created are given not existing in current context.
then it gives error
Error :The name 'InitializeComponent' does not exist in the current context
Could some one please help me in achieving the same in c# silverlight web application ? Would be a big help,thanks.
Here is a Example.
namespace check
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
// Use the generic type Test with an int type parameter.
Test<int> Test1 = new Test<int>(5);
// Call the Write method.
Test1.Write();
// Use the generic type Test with a string type parameter.
Test<string> Test2 = new Test<string>("cat");
Test2.Write();
}
}
class Test<T>
{
T _value;
public Test(T t)
{
// The field has the same type as the parameter.
this._value = t;
}
public void Write()
{
MessageBox.Show(this._value);
}
}
}
I think you asking this kind of example.
You can use generic as if you don’t use XAML. But if you want to use XAML to define your control, you can’t use generic. That's why the problem is occurs.
Create a another class and use it. I think It's help you.

Why aren't my class library methods appearing in my referenced console application?

I have written a class library. To execute methods that I wrote in my class library, I created a console application. In my console application, I added the class library that I wrote as a reference. I then added the appropriate using statement to my console application. My methods from this library are inaccessible currently. Why?
Here's my class library with a basic method. It was created in .NET framework 3.5.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Geometry;
namespace RelateTablesValidation
{
[Guid("e1058544-0d84-49be-a406-b4e65707f95b")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("RelateTablesValidation.Validate")]
[ComVisible(true)]
public class Validate : ESRI.ArcGIS.Geodatabase.IClassExtension, ESRI.ArcGIS.Geodatabase.IObjectClassExtension, ESRI.ArcGIS.Geodatabase.IRelatedObjectClassEvents2
{
public void ChangeClassExtension(IObjectClass objectClass, String extensionUID, IPropertySet extensionProperties)
{
ISchemaLock schemaLock = (ISchemaLock)objectClass;
try
{
// Attempt to get an exclusive schema lock.
schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
// Cast the object class to the IClassSchemaEdit2 interface.
IClassSchemaEdit2 classSchemaEdit = (IClassSchemaEdit2)objectClass;
if (!String.IsNullOrEmpty(extensionUID))
{
// Create a unique identifier (UID) object and change the extension.
UID extUID = new UIDClass();
extUID.Value = extensionUID;
classSchemaEdit.AlterClassExtensionCLSID(extUID, extensionProperties);
}
else
{
// Clear the class extension.
classSchemaEdit.AlterClassExtensionCLSID(null, null);
}
}
catch (COMException comExc)
{
throw new Exception("Could not change class extension.", comExc);
}
finally
{
schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
}
}
}
Here's my console app. RelateTablesValidation is the class library. Also created in .NET Framework 3.5
using System;
using System.Collections.Generic;
using System.Text;
using RelateTablesValidation;
using Esri.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DatasourcesGDB;
namespace ApplyClassExtension
{
class Program
{
[STAThread()]
static void Main(string[] args)
{
//system sees objects from this namespace OK
IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
//now when i try to call my method, it doesn't even show up in Intellisense
ChangeClassExtension(method params would go here);
}
}
}
You can't do what you're trying to do.
All methods in C# are inside of objects. You must either make the method static and call it like this:
Validate.ChangeClassExtension(...);
Or don't make it static and instantiate an instance of Validate:
var val = new Validate();
val.ChangeClassExtension(...);

InvalidCastException, DLLs and reflection trouble in C#

I'm trying to use a precompiled DLL with reflection, to instantiate an interface for my class that is in the DLL. I tried by the book, but it won't work. It throws InvalidCastException when I try to do something like:
ICompute iCompute = (ICompute)Activator.CreateInstance(type);
Where type of course is my class that implements ICompute interface. I'm stuck and don't know what to do. The complete code follows:
This is the DLL content:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication18
{
public class ClassThatImplementsICompute : ICompute
{
public int sumInts(int term1, int term2)
{
return term1 + term2;
}
public int diffInts(int term1, int term2)
{
return term1 - term2;
}
}
}
The actual program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ConsoleApplication18
{
public interface ICompute
{
int sumInts(int term1, int term2);
int diffInts(int term1, int term2);
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Loading dll...");
Assembly assembly = Assembly.LoadFrom("mylib.dll");
Console.WriteLine("Getting type...");
Type type = assembly.GetType("ConsoleApplication18.ClassThatImplementsICompute");
if (type == null) Console.WriteLine("Could not find class type");
Console.WriteLine("Instantiating with activator...");
//my problem!!!
ICompute iCompute = (ICompute)Activator.CreateInstance(type);
//code that uses those functions...
}
}
}
Can anyone help me? Thanks!
The problem is to do with how you load the assembly with Assembly.LoadFrom().
LoadFrom() load the assembly into different context compared to context of the ICompute interface you are trying to cast to. Try to use Assembly.Load() instead if possible. i.e. put the assembly into the bin / probing path folder and load by the full strong name.
Some references:
http://msdn.microsoft.com/en-us/library/dd153782.aspx
http://blogs.msdn.com/b/suzcook/archive/2003/05/29/57143.aspx (see the disadvantage bit for LoadFrom)

Categories

Resources