Search Results

Search found 24043 results on 962 pages for 'private methods'.

Page 64/962 | < Previous Page | 60 61 62 63 64 65 66 67 68 69 70 71  | Next Page >

  • HandsOnTable - using date functions with methods

    - by briansol
    I have a function used on the datepicker to limit dates selected to the first of the month... I invoke it by setting a class and listener, such as: $( ".datepickfom" ).datepicker( { beforeShowDay: fom, showOn: "both", buttonImage: "/images/calendar.png", buttonImageOnly: true, changeMonth: true, changeYear: true, dateFormat: "m/d/yy", yearRange: "-25:+100", constrainInput: true } ); the fom call: function fom(date){ if (date.getDate() != 1) { return [false, "", "Specify 1st of Month"]; } return [true, ""]; } This works great for regular forms. I'm looking to extend this functionality to the HandsOnTable 'date' cell data types. var $container_1 = $("#datatable_1"); var handsontable_1 = $container_1.data('handsontable'); $("#datatable_1").handsontable( { columns: [ {}, {}, { type: 'date', dateFormat: 'm/d/yy' }, {}, { type: 'dropdown', source: ["","Y","N"] }, {}, {} ] }); This also works as it should, but the date lets me pick other dates besides the first. Is there a way to attach the beforeShowDay option to the HOT cell call as well?

    Read the article

  • Find and list all functions/methods in a set of JavaScript files

    - by Dan Milstein
    Is there a way to read a set of JavaScript files, and output a description of where every function/method is defined? I realize that this is likely impossible in full generality, due to the extreme dynamic nature of the language. What I'm imagining is something which gets the (relatively) straightforward cases. Ideally, I'd want it figure out where, e.g. some method got attached to string or hash or some other fundamental class (and also just let you find all the classes/functions that get defined once in one place). Does such a tool exist?

    Read the article

  • Any method to denote object assignment?

    - by Droogans
    I've been studying magic methods in Python, and have been wondering if there's a way to outline the specific action of: a = MyClass(*params).method() versus: MyClass(*params).method() In the sense that, perhaps, I may want to return a list that has been split on the '\n' character, versus dumping the raw list into the variable a that keeps the '\n' intact. Is there a way to ask Python if its next action is about to return a value to a variable, and change action, if that's the case? I was thinking: class MyClass(object): def __init__(*params): self.end = self.method(*params) def __asgn__(self): return self.method(*params).split('\n') def __str__(self): """this is the fallback if __asgn__ is not called""" return self.method(*params)

    Read the article

  • "Method name expected" error when trying add a handler method to a delegate - C#

    - by zakplayyy
    I keep getting the error "Method name expected" when trying add the a method to a delegate. I have a delegate which is invoked when ever my game ends. The function I'm trying to add to the delegate stops a countdown from flashing (the method is in a static class). I've searched about and I'm still unsure why its not working. Here is the line causing the error: LivesManager.gameEnded += new LivesManager.EndGame(CountdownManager.DisableFlashTimer(this)); The this passes the current form to the method so it can disable the timer flash on the form. I have added methods from static classes to the same delegate before and it works fine, the only difference is that I'm passing the form as a paramater and then it doesn't like it. Is there any way to pass the form to the method without the error? Thanks in advance :)

    Read the article

  • PHP forms $_GET and $_POST methods

    - by user294705
    After I select the checkbox and press the button, the result data should display in the other page.I need to know the way I do this in php. My querry is working fine in the database and It shows the results.Now I need to display those results in the other page after selecting the first page checkbox and button(relevent to that checkbox).

    Read the article

  • Enhance Predfined Methods in Scala

    - by fratnk
    Base question: Why can I write in Scala just: println(10) Why don't I need to write: Console println(10) Followup question: How can I introduce a new method "foo" which is everywhere visible and usable like "println"?

    Read the article

  • Do these methods have same output?

    - by devrimbaris
    protected synchronized boolean isTimeoutOccured(Duration timeoutDuration) { DateTime now = new DateTime(); if (timeoutOccured == false) { if (new Duration(requestTime.getMillis(), now.getMillis()).compareTo(timeoutDuration) > 0) { timeoutOccured = true; } } return timeoutOccured; } protected boolean isTimeoutOccured2(Duration timeoutDuration) { return atomicTimeOut.compareAndSet(false, new Duration(requestTime.getMillis(), new DateTime().getMillis()).compareTo(timeoutDuration) > 0); }

    Read the article

  • Best Methods for Dynamically Creating New Objects

    - by frankV
    I'm looking for a method to dynamically create new class objects during runtime of a program. So far what I've read leads me to believe it's not easy and normally reserved for more advanced program requirements. What I've tried so far is this: // create a vector of type class vector<class_name> vect; // and use push_back (method 1) vect.push_back(*new Object); //or use for loop and [] operator (method 2) vect[i] = *new Object; neither of these throw errors from the compiler, but I'm using ifstream to read data from a file and dynamically create the objects... the file read is taking in some weird data and occasionally reading a memory address, and it's obvious to me it's due to my use/misuse of the code snippet above. The file read code is as follows: // in main ifstream fileIn fileIn.open( fileName.c_str() ); // passes to a separate function along w/ vector loadObjects (fileIn, vect); void loadObjects (ifstream& is, vector<class_name>& Object) { int data1, data2, data3; int count = 0; string line; if( is.good() ){ for (int i = 0; i < 4; i++) { is >> data1 >> data2 >> data3; if (data1 == 0) { vect.push_back(*new Object(data2, data3) ) } } } }

    Read the article

  • Are high office partitions as effective as private offices?

    - by CraigS
    I'm currently reading DeMarco and Lister's Peopleware, and I've been struck (as everyone is) by their comments about noise reduction via using private offices, and the effect this has on productivity. Private offices are probably not going to happen at my workplace, but I'm wondering if high cubicle partitions (say, 6 feet) might be nearly as good? I imagine they wouldn't deflect quite as much noise, but they would have some effect. One down-side is that the center cubicles would have less natural light. That seems quite a big downer to me. I'd be interested to hear what peoples experiences are.

    Read the article

  • Snake Game Help

    - by MuhammadA
    I am making a snake game and learning XNA at the same time. I have 3 classes : Game.cs, Snake.cs and Apple.cs My problem is more of a conceptual problem, I want to know which class is really responsible for ... detecting collision of snake head on apple/itself/wall? which class should increase the snakes speed, size? It seems to me that however much I try and put the snake stuff into snake.cs that game.cs has to know a lot about the snake, like : -- I want to increase the score depending on size of snake, the score variable is inside game.cs, which means now I have to ask the snake its size on every hit of the apple... seems a bit unclean all this highly coupled code. or -- I DO NOT want to place the apple under the snake... now the apple suddenly has to know about all the snake parts, my head hurts when I think of that. Maybe there should be some sort of AppleLayer.cs class that should know about the snake... Whats the best approach in such a simple scenario? Any tips welcome. Game.cs : using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Design; namespace Snakez { public enum CurrentGameState { Playing, Paused, NotPlaying } public class Game1 : Microsoft.Xna.Framework.Game { private GraphicsDeviceManager _graphics; private SpriteBatch _spriteBatch; private readonly Color _niceGreenColour = new Color(167, 255, 124); private KeyboardState _oldKeyboardState; private SpriteFont _scoreFont; private SoundEffect _biteSound, _crashSound; private Vector2 _scoreLocation = new Vector2(10, 10); private Apple _apple; private Snake _snake; private int _score = 0; private int _speed = 1; public Game1() { _graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { _spriteBatch = new SpriteBatch(GraphicsDevice); _scoreFont = Content.Load<SpriteFont>("Score"); _apple = new Apple(800, 480, Content.Load<Texture2D>("Apple")); _snake = new Snake(Content.Load<Texture2D>("BodyBlock")); _biteSound = Content.Load<SoundEffect>("Bite"); _crashSound = Content.Load<SoundEffect>("Crash"); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { Content.Unload(); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { KeyboardState newKeyboardState = Keyboard.GetState(); if (newKeyboardState.IsKeyDown(Keys.Escape)) { this.Exit(); // Allows the game to exit } else if (newKeyboardState.IsKeyDown(Keys.Up) && !_oldKeyboardState.IsKeyDown(Keys.Up)) { _snake.SetDirection(Direction.Up); } else if (newKeyboardState.IsKeyDown(Keys.Down) && !_oldKeyboardState.IsKeyDown(Keys.Down)) { _snake.SetDirection(Direction.Down); } else if (newKeyboardState.IsKeyDown(Keys.Left) && !_oldKeyboardState.IsKeyDown(Keys.Left)) { _snake.SetDirection(Direction.Left); } else if (newKeyboardState.IsKeyDown(Keys.Right) && !_oldKeyboardState.IsKeyDown(Keys.Right)) { _snake.SetDirection(Direction.Right); } _oldKeyboardState = newKeyboardState; _snake.Update(); if (_snake.IsEating(_apple)) { _biteSound.Play(); _score += 10; _apple.Place(); } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(_niceGreenColour); float frameRate = 1 / (float)gameTime.ElapsedGameTime.TotalSeconds; _spriteBatch.Begin(); _spriteBatch.DrawString(_scoreFont, "Score : " + _score, _scoreLocation, Color.Red); _apple.Draw(_spriteBatch); _snake.Draw(_spriteBatch); _spriteBatch.End(); base.Draw(gameTime); } } } Snake.cs : using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace Snakez { public enum Direction { Up, Down, Left, Right } public class Snake { private List<Rectangle> _parts; private readonly Texture2D _bodyBlock; private readonly int _startX = 160; private readonly int _startY = 120; private int _moveDelay = 100; private DateTime _lastUpdatedAt; private Direction _direction; private Rectangle _lastTail; public Snake(Texture2D bodyBlock) { _bodyBlock = bodyBlock; _parts = new List<Rectangle>(); _parts.Add(new Rectangle(_startX, _startY, _bodyBlock.Width, _bodyBlock.Height)); _parts.Add(new Rectangle(_startX + bodyBlock.Width, _startY, _bodyBlock.Width, _bodyBlock.Height)); _parts.Add(new Rectangle(_startX + (bodyBlock.Width) * 2, _startY, _bodyBlock.Width, _bodyBlock.Height)); _parts.Add(new Rectangle(_startX + (bodyBlock.Width) * 3, _startY, _bodyBlock.Width, _bodyBlock.Height)); _direction = Direction.Right; _lastUpdatedAt = DateTime.Now; } public void Draw(SpriteBatch spriteBatch) { foreach (var p in _parts) { spriteBatch.Draw(_bodyBlock, new Vector2(p.X, p.Y), Color.White); } } public void Update() { if (DateTime.Now.Subtract(_lastUpdatedAt).TotalMilliseconds > _moveDelay) { //DateTime.Now.Ticks _lastTail = _parts.First(); _parts.Remove(_lastTail); /* add new head in right direction */ var lastHead = _parts.Last(); var newHead = new Rectangle(0, 0, _bodyBlock.Width, _bodyBlock.Height); switch (_direction) { case Direction.Up: newHead.X = lastHead.X; newHead.Y = lastHead.Y - _bodyBlock.Width; break; case Direction.Down: newHead.X = lastHead.X; newHead.Y = lastHead.Y + _bodyBlock.Width; break; case Direction.Left: newHead.X = lastHead.X - _bodyBlock.Width; newHead.Y = lastHead.Y; break; case Direction.Right: newHead.X = lastHead.X + _bodyBlock.Width; newHead.Y = lastHead.Y; break; } _parts.Add(newHead); _lastUpdatedAt = DateTime.Now; } } public void SetDirection(Direction newDirection) { if (_direction == Direction.Up && newDirection == Direction.Down) { return; } else if (_direction == Direction.Down && newDirection == Direction.Up) { return; } else if (_direction == Direction.Left && newDirection == Direction.Right) { return; } else if (_direction == Direction.Right && newDirection == Direction.Left) { return; } _direction = newDirection; } public bool IsEating(Apple apple) { if (_parts.Last().Intersects(apple.Location)) { GrowBiggerAndFaster(); return true; } return false; } private void GrowBiggerAndFaster() { _parts.Insert(0, _lastTail); _moveDelay -= (_moveDelay / 100)*2; } } } Apple.cs : using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace Snakez { public class Apple { private readonly int _maxWidth, _maxHeight; private readonly Texture2D _texture; private readonly Random random = new Random(); public Rectangle Location { get; private set; } public Apple(int screenWidth, int screenHeight, Texture2D texture) { _maxWidth = (screenWidth + 1) - texture.Width; _maxHeight = (screenHeight + 1) - texture.Height; _texture = texture; Place(); } public void Place() { Location = GetRandomLocation(_maxWidth, _maxHeight); } private Rectangle GetRandomLocation(int maxWidth, int maxHeight) { // x and y -- multiple of 20 int x = random.Next(1, maxWidth); var leftOver = x % 20; x = x - leftOver; int y = random.Next(1, maxHeight); leftOver = y % 20; y = y - leftOver; return new Rectangle(x, y, _texture.Width, _texture.Height); } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(_texture, Location, Color.White); } } }

    Read the article

  • What are the pros and cons of public sector vs private sector software development? [closed]

    - by j.i.h.
    I'm currently considering a job working for my state of residence. However, besides the obvious drawback of far less compensation than I could get in the private sector, are there any other drawbacks? Are there any upsides to public work, besides helping society at large and benefits? My main concern is that if I work in the public sector, I might be stained with the perception that I "got along" in an uncompetitive environment. I have no idea if this would be the actual environment, but it seems to be the preconception about government work--unionized workers who are simply there because the union keeps them from being fired. So, does anyone have experience working for the government? Do you have experiences working with people transitioning from public to private sector?

    Read the article

  • Silverlight UserControl with rectangle as a button

    - by Rafal
    Hi, I have a problem using custom made UserControl in Silverlight Page. The UserControl is generally a rectangle containing a smaller rectangle inside. I want to use the UControl in a Silverlight MainSite. i've implemented a method on mouse button down for a smaller rectangle called in here Button1: public void Button1_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { MessageBox.Show("Hello"); } How can i use it from a MainSite? From there I can only implement a method like: private void ImportedControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { firstLeaf.Button1_MouseLeftButtonDown(sender, e); } I can not implement a method for Button1. How can i mek this Work? HELP:)

    Read the article

  • Why won't my anonymous function fire on grid.prerender?

    - by adam0101
    In my gridview I have fields for inserting a new record in the footer. In my objectdatasource selecting event if no records came back I bind a single mock row to force the footer to show so they can still add records. Since the row does not contain real data I hide the row. ... If result.ItemCount = 0 Then result = mockRow AddHandler mygridview.PreRender, AddressOf HideRow End If End Sub Private Sub HideRow(ByVal sender as Object, ByVal e as EventArgs) mygridview.Rows(0).Visible = False End Sub This works fine. However, I'd like to condense it like this: ... If result.ItemCount = 0 Then result = mockRow AddHandler mygridview.PreRender, Function() mygridview.Rows(0).Visible = False End If End Sub This compiles fine, but the row doesn't get hidden. Can anyone tell me why my anonymous function isn't getting hit?

    Read the article

  • Hiding members in a C struct

    - by Marlon
    I've been reading about OOP in C but I never liked how you can't have private data members like you can in C++. But then it came to my mind that you could create 2 structures. One is defined in the header file and the other is defined in the source file. // ========================================= // in somestruct.h typedef struct { int _public_member; } SomeStruct; // ========================================= // in somestruct.cpp #include "somestruct.h" typedef struct { int _public_member; int _private_member; } SomeStructSource; SomeStruct *SomeStruct_Create() { SomeStructSource *p = (SomeStructSource *)malloc(sizeof(SomeStructSource)); p->_private_member = 0xWHATEVER; return (SomeStruct *)p; } From here you can just cast one structure to the other. Is this considered bad practice? Or is it done often? (I think this is done with a lot of the structures when using the Win32 API, but you guys are the experts let me know!)

    Read the article

  • [PHP] using the magic __set() method with 2D arrays

    - by Spoonface
    If I have the following registry class: Class registry { private $_vars; public function __construct() { $this->_vars = array(); } public function __set($key, $val) { $this->_vars[$key] = $val; } public function __get($key) { if (isset($this->_vars[$key])) return $this->_vars[$key]; } public function printAll() { print "<pre>".print_r($this->_vars,true)."</pre>"; } } $reg = new registry(); $reg->arr = array(1,2,3); $reg->arr = array_merge($reg->arr,array(4)); $reg->printAll(); Would there be an easier way to push a new item onto the 'arr' array? This code: 'array[] = item' doesn't work with the magic set method, and I couldn't find any useful info with google. Thanks for your time!

    Read the article

  • Error : Implementation for method missing (Delphi Prism)

    - by Ilya
    I wrote my method: LangChange type MainForm = partial class(System.Windows.Forms.Form) private ... method LangChange(); protected method Dispose(disposing: Boolean); override; public constructor; end; implementation ... method LangChange(); begin ... end; However,I have an error Error 1 (PE33) Implementation for method "Compiler.MainForm.LangChange" missing What is wrong?Help please!

    Read the article

  • Ruby on Rails with_option cannot call class method

    - by Dmitri
    I have a problem calling class method from the with_option block with validations: Model: class Model < ActiveRecord::Base attr_accessible :field with_options :if => "<not important>" do |step| ... bunch of validations step.validates :field, :inclusion => {:within => Model.field} end private self.field (1..10) end end And it returns: undefined method `field' for #Class:0x5f394a8 self.class.field also doesn't work. What is wrong with it ? How to fix it ? Big big thanks!

    Read the article

  • Can fields of the class and arguments of the method interfere?

    - by Roman
    I have a class with a fields called "a". In the class I have a method and in the list of arguments of this method I also have "a". So, which "a" I will see inside of the method? Will it be the field or it will be the argument of the method? public class myClass { private String a; // Method which sets the value of the field "a". public void setA(String a) { a = a; } } By the way, there is a similar situation. A method has some local (for method) variables whose names coincide with the names of the fields. What will the "see" the method if I refer to such a method-local variable inside the method (the field or the local variable)?

    Read the article

  • c# passing method names as the argument in a method

    - by Alan Bennett
    hi guys, I have a recuring method which shows up many times in my code its basically checking to make sure that the connection to the odbc is ok and then connects but each time this method is called it calls another method and each instance of the main method this one is different, as each method is about 8 lines of code having it 8 times in the code isnt ideal. so basically i would like to have just one method which i can call passing the name of the new method as an arguement. so basically like: private void doSomething(methodToBeCalled) { if(somthingistrue) { methodToBeCalled(someArgument) } } is this possible? thanks in advance

    Read the article

  • Pattern for database-wrapper in java

    - by Space_C0wb0y
    I am currently writing a java-class that wraps an SQLite database. This class has two ways to be instantiated: Open an existing database. Create a new database. This is what I cam up with: public class SQLiteDatabaseWrapper { public static SQLiteDatabaseWrapper openExisting(File PathToDB) { return new SQLiteDatabaseWrapper(PathToDB); } public static SQLiteDatabaseWrapper createNew(File PathToDB) { CreateAndInitializeNewDatabase(PathToDB); return new SQLiteDatabaseWrapper(PathToDB); } private SQLiteDatabaseWrapper(File PathToDB) { // Open connection and setup wrapper } } Is this the way to go in Java, or is there any other best practice for this situation?

    Read the article

  • Pass form object value to static method

    - by jrubengb
    Hi, I need to take a form object value and pass it into a static method: public void SetCalendarStartSafe(DateTime startDateSafe) { startDateSafe = calendarStart.Value; } private static DataTable GetData() { frmMain frm = new frmMain(); DateTime startDate = new frmMain(); frm.SetCalendarStartSafe(startDate); } However I keep getting today's current date whenever I try this approach, even if the specified calendar date on the form is different. How can I can the user-specified calendar date from the original frmMain object? Thanks in advance for any guidance.

    Read the article

  • How to break WinDbg in an anonymous method?

    - by Richard Berg
    Title kinda says it all. The usual SOS command !bpmd doesn't do a lot of good without a name. Some ideas I had: dump every method, then use !bpmd -md when you find the corresponding MethodDesc not practical in real world usage, from what I can tell. Even if I wrote a macro to limit the dump to anonymous types/methods, there's no obvious way to tell them apart. use Reflector to dump the MSIL name doesn't help when dealing with dynamic assemblies and/or Reflection.Emit. Visual Studio's inability to read local vars inside such scenarios is the whole reason I turned to Windbg in the first place... set the breakpoint in VS, wait for it to hit, then change to Windbg using the noninvasive trick attempting to detach from VS causes it to hang (along with the app). I think this is due to the fact that the managed debugger is a "soft" debugger via thread injection instead of a standard "hard" debugger. Or maybe it's just a VS bug specific to Silverlight (would hardly be the first I've encountered). set a breakpoint on some other location known to call into the anonymous method, then single-step your way in my backup plan, though I'd rather not resort to it if this Q&A reveals a better way

    Read the article

  • Generic wrapper for System.Web.Caching.Cache functions

    - by David Neale
    I've created a generic wrapper for using the Cache object: public class Cache<T> where T : class { public Cache Cache {get;set;} public CachedKeys Key {get;set;} public Cache(Cache cache, CachedKeys key){ Cache = cache; Key = key; } public void AddToCache(T obj){ Cache.Add(Key.ToString(), obj, null, DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); } public bool TryGetFromCache(out T cachedData) { cachedData = Cache[Key.ToString()] as T; return cachedData != null; } public void RemoveFromCache() { Cache.Remove(Key.ToString()); } } The CachedKeys enumeration is just a list of keys that can be used to cache data. The trouble is, to call it is quite convuluted: var cache = new Cache<MyObject>(Page.Cache, CachedKeys.MyKey); MyObject myObject = null; if(!cache.TryGetFromCache(out myObject)){ //get data... cache.AddToCache(data); //add to cache return data; } return myObject; I only store one instance of each of my objects in the cache. Therefore, is there any way that I can create an extension method that accepts the type of object to Cache and uses (via Reflection) its Name as the cache key? public static Cache<T> GetCache(this Cache cache, Type cacheType){ Cache<cacheType> Cache = new Cache<cacheType>(cache, cacheType.Name); } Of course, there's two errors here: Extension methods must be defined in a non-generic static class The type or namespace name 'cacheType' could not be found This is clearly not the right approach but I thought I'd show my working. Could somebody guide me in the right direction?

    Read the article

  • Is there a better way to create a generic convert string to enum method or enum extension?

    - by Kelsey
    I have the following methods in an enum helper class (I have simplified it for the purpose of the question): static class EnumHelper { public enum EnumType1 : int { Unknown = 0, Yes = 1, No = 2 } public enum EnumType2 : int { Unknown = 0, Dog = 1, Cat = 2, Bird = 3 } public enum EnumType3 : int { Unknown = 0, iPhone = 1, Andriod = 2, WindowsPhone7 = 3, Palm = 4 } public static EnumType1 ConvertToEnumType1(string value) { return (string.IsNullOrEmpty(value)) ? EnumType1.Unknown : (EnumType1)(Enum.Parse(typeof(EnumType1), value, true)); } public static EnumType2 ConvertToEnumType2(string value) { return (string.IsNullOrEmpty(value)) ? EnumType2.Unknown : (EnumType2)(Enum.Parse(typeof(EnumType2), value, true)); } public static EnumType3 ConvertToEnumType3(string value) { return (string.IsNullOrEmpty(value)) ? EnumType3.Unknown : (EnumType3)(Enum.Parse(typeof(EnumType3), value, true)); } } So the question here is, can I trim this down to an Enum extension method or maybe some type of single method that can handle any type. I have found some examples to do so with basic enums but the difference in my example is all the enums have the Unknown item that I need returned if the string is null or empty (if no match is found I want it to fail). Looking for something like the following maybe: EnumType1 value = EnumType1.Convert("Yes"); // or EnumType1 value = EnumHelper.Convert(EnumType1, "Yes"); One function to do it all... how to handle the Unknown element is the part that I am hung up on.

    Read the article

< Previous Page | 60 61 62 63 64 65 66 67 68 69 70 71  | Next Page >